Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package purluno.springrain.book
- import javax.annotation.Resource
- import org.hibernate.Session
- import org.springframework.stereotype.Service
- import purluno.springrain.HibernateHelper
- @Service
- class BookService {
- static final int DEFAULT_PAGE_SIZE = 3
- int pageSize = DEFAULT_PAGE_SIZE
- /**
- * Hibernate 지원 객체
- */
- @Resource
- HibernateHelper hib
- /**
- * 특정 id의 책 정보를 가져온다.
- *
- * @param id
- * 책 정보 ID
- * @return
- * 책 정보 객체. 또는, 책이 없을 경우 null.
- */
- Book getById(long id) {
- hib.transactional { Session session ->
- session.get(Book, id)
- }
- }
- /**
- * 특정 ISBN을 가진 책 정보를 가져온다.
- *
- * @param isbn
- * ISBN
- * @return
- * 책 정보 객체. 또는, 책이 없을 경우 null.
- */
- Book getByIsbn(String isbn) {
- assert isbn != null, "ISBN은 null이 아니어야 합니다."
- assert !isbn.empty, "ISBN은 빈 문자열이 아니어야 합니다."
- hib.transactional { Session session ->
- session.bySimpleNaturalId(Book).load(isbn)
- }
- }
- /**
- * 책 정보의 총 개수를 구한다.
- */
- int count() {
- hib.transactional { Session session ->
- def hql = "select count(*) from Book"
- session.createQuery(hql).uniqueResult()
- }
- }
- /**
- * 책 정보 목록을 가져온다.
- * 인자로 받는 params로부터 요청 페이지(page)를 입력받으며,
- * params에 개수(count), 페이지 수(numPages), 현재 페이지(page), 페이지 크기(pageSize)를
- * 지정한다.
- */
- List<Book> list(Map params) {
- hib.transactional { Session session ->
- def c = count()
- def numPages = (c - 1).intdiv(pageSize) + 1
- def page = Math.min(Math.max(1, params["page"]), numPages)
- def first = (page - 1) * pageSize
- params["count"] = c
- params["numPages"] = numPages
- params["page"] = page
- params["pageSize"] = pageSize
- params["startPage"] = Math.max(1, page - 5)
- params["endPage"] = Math.min(page + 5, numPages)
- params["first"] = first
- def hql = "from Book order by dateModified desc"
- session.createQuery(hql)
- .setFirstResult(first)
- .setMaxResults(pageSize)
- .list()
- }
- }
- /**
- * 책 정보를 생성한다.
- *
- * @param book
- */
- void save(Book book) {
- if (book.isbn?.empty) { // ISBN이 비어있으면
- book.isbn = null // 중복될 수 있도록 null 처리해준다.
- }
- hib.transactional { Session session ->
- def now = new Date()
- book.dateCreated = now
- book.dateModified = now
- session.save(book)
- }
- }
- /**
- * 책 정보를 갱신한다.
- *
- * @param input
- */
- void update(Book input) {
- assert input.id != null, "ID는 null이 아니어야 합니다."
- if (input.isbn?.empty) { // ISBN이 비어있으면
- input.isbn = null // 중복될 수 있도록 null 처리해준다.
- }
- hib.transactional { Session session ->
- Book book = session.get(Book, input.id)
- book.dateModified = new Date()
- book.isbn = input.isbn
- book.title = input.title
- book.author = input.author
- book.year = input.year
- book.intro = input.intro
- book.authorIntro = input.authorIntro
- }
- }
- /**
- * 책 정보를 삭제한다.
- *
- * @param id
- * 삭제할 책 정보의 ID
- */
- void delete(long id) {
- hib.transactional { Session session ->
- session.delete(new Book(id: id))
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement