Hibernate中的分頁查詢
阿新 • • 發佈:2019-01-14
一、hibernate分頁查詢:
方法:
setFirstResult:設定查詢開始的記錄 setMaxResults:設定每次查詢的條數 /** * 查詢全部文章的過載 * 分頁查詢 * @param currentPage 當前頁面 * @param maxResults 每頁最大條數 * @return */ public List<Article> findAllArticle(Integer currentPage,Integer maxResults ) { String hql = "FROM Article" ; //如果要根據外來鍵的欄位進行分頁查詢,則應該是 //String hql = "From Article WHERE user.userId=xxx ;這裡的user是Article類中外來鍵的物件引用 Query query = session.createQuery(hql) ; //設定開始查詢的物件索引 當前頁面-1 乘以每頁最大條目數 query.setFirstResult((currentPage-1)*maxResults) ; //設定每頁最大條目數 query.setMaxResults(maxResults) ; return query.list() ; }
二、hibernateTemlate的分頁查詢(多使用這種方法,簡便)
1.有條件的分頁查詢
public List<Draft> findAllDraft(Integer authorId , Integer currentPage, Integer maxResults) { Draft draft = new Draft() ; draft.setAuthorId(authorId); //這是要設定的條件,滿足這個條件的會被分頁查找出來 return hibernateTemplate.findByExample(draft, (currentPage-1)*maxResults, maxResults) ; 注意!findByExample方法會忽略掉物件draft中的null值,就是說如果屬性為null,就不會將該屬性寫入sql語句的條件中。 但是!基本型別的預設值不是null,而是0!所以,如果存在除了主鍵外的基本型別,那麼將會被寫進到sql語句的條件中。 因此,在使用的物件的類中(draft物件的類Draft),不要用基本型別,而要用包裝類,防止在這個時候導致查詢不到結果 }
2.查詢所有的分頁查詢(detachedCriteria)
public List<Dustbin> findAllDustbin(Integer currentPage, Integer MAXRESULTS) { DetachedCriteria criteria = DetachedCriteria.forClass(Dustbin.class) ; return (List<Dustbin>) hibernateTemplate.findByCriteria(criteria, (currentPage-1)*MAXRESULTS, MAXRESULTS) ; }
方法是findByCriteria方法
利用了detachedCriteria物件,該物件不用從session裡獲取,但可以用任意一個session方法使用