Skip to content

Instantly share code, notes, and snippets.

@bmakarand2009
Last active August 29, 2015 13:56
Show Gist options
  • Save bmakarand2009/8840383 to your computer and use it in GitHub Desktop.
Save bmakarand2009/8840383 to your computer and use it in GitHub Desktop.
Hibernate Iterate throught Batches
//The query for the books:
//Reference : http://www.laliluna.de/articles/java-persistence-hibernate/performance-tips-hibernate-java-persistence.html
List<Book> books = session.createQuery(
“from Book b where b.name like ?”).setString(0, “Java%”).list();
/* The following code printing the books will create one SQL query per
book to initialize the chapters. We get 1+n queries in total. One for
the books and n for the chapters, if we have n books.
*/
for (Book book : books) {
int totalLength = 0;
for (Chapter chapter : book.getChapters()) {
totalLength += (chapter.getContent() != null ?
chapter.getContent().length() : 0);
}
log.info("Length of all chapters: " + totalLength);
}
//Solution
/* One way to improve this is to define
that Hibernate loads the chapters in batches. Here is the mapping:
Annotations
*/
OneToMany(cascade = CascadeType.ALL) <br>JoinColumn(nullable = false)
@BatchSize(size = 4)
private Set<Chapter> chapters = new HashSet<Chapter>();
//Also, the same can also be solved with CRITERIA QUERY
//The same with a criteria query:
List<Book> books = session.createCriteria(Book.class)
.setFetchMode(”chapters", org.hibernate.FetchMode.JOIN)
.add(Restrictions.like(“name”, “Java”, MatchMode.START))
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment