Last active
August 29, 2015 13:56
-
-
Save bmakarand2009/8840383 to your computer and use it in GitHub Desktop.
Hibernate Iterate throught Batches
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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