hooliooo
04/28/2020, 1:30 PMList<Post> posts = doInJPA(entityManager -> {
List<Post> _posts = entityManager
.createQuery(
"select distinct p " +
"from Post p " +
"left join fetch p.comments " +
"where p.id between :minId and :maxId ", Post.class)
.setParameter("minId", 1L)
.setParameter("maxId", 50L)
.setHint(QueryHints.PASS_DISTINCT_THROUGH, false)
.getResultList();
_posts = entityManager
.createQuery(
"select distinct p " +
"from Post p " +
"left join fetch p.tags t " +
"where p in :posts ", Post.class)
.setParameter("posts", _posts)
.setHint(QueryHints.PASS_DISTINCT_THROUGH, false)
.getResultList();
return _posts;
});
assertEquals(POST_COUNT, posts.size());
for(Post post : posts) {
assertEquals(POST_COMMENT_COUNT, post.getComments().size());
assertEquals(TAG_COUNT, post.getTags().size());
}
And explains the following:
Now, we have to fetch the Post entities along with their associated Tag entities, and, thanks to the Persistence Context, Hibernate will set the tags collection of the previously fetched Post entities.
But when I use the logic in Kotlin:
val companiesWithAddresses = entityManager.createQuery(
"""
SELECT t from ProjectCompany t
LEFT JOIN FETCH t.addresses
ORDER BY t.id ASC
""",
ProjectCompany::class.java
)
.setHint(QueryHints.PASS_DISTINCT_THROUGH, false)
.resultList
val companies = entityManager.createQuery(
"""
SELECT t from ProjectCompany t
LEFT JOIN FETCH t.contactPersons persons
WHERE t in :companies
ORDER BY t.id ASC
""",
ProjectCompany::class.java
)
.setParameter("companies", companiesWithAddresses)
.setHint(QueryHints.PASS_DISTINCT_THROUGH, false)
.resultList
return PageImpl(companies, pageable, companies.size.toLong())
I get this error:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ProjectCompany.addresses, could not initialize proxy - no Session