0

I am having the following read method in my repository

@Query("SELECT new com...ContentStores(news.id, news.stores, news.storesOrigin) FROM AbstractNewsContent news WHERE news.storesOrigin.id in :storesOriginIds AND news.createDate >= :startDate")
List<ContentStores> findNewsByStoresOriginIdsInPeriod(@Param("storesOriginIds") Set<Long> storesOriginIds, @Param("startDate") Instant startDate); 

It produces org.hibernate.LazyInitializationException: could not initialize proxy [com...StoresOrigin#592] - no Session

Ok, it is because of the lazy initialisation of the field (it is desired behaviour)

@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "STORES_ORIGIN_ID")
protected StoresOrigin storesOrigin;

Then I read more about how to solve this problem and I have added 'LEFT JOIN FETCH news.storesOrigin' and it looks like:

@Query("SELECT new com...ContentStores(news.id, news.stores, news.storesOrigin) FROM AbstractNewsContent news LEFT JOIN FETCH news.storesOrigin WHERE news.storesOrigin.id in :storesOriginIds AND news.createDate >= :startDate")
List<ContentStores> findNewsByStoresOriginIdsInPeriod(@Param("storesOriginIds") Set<Long> storesOriginIds, @Param("startDate") Instant startDate);

And I got the following while building the project:

Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: 
query specified join fetching, but the owner of the fetched association 
was not present in the select list 
[FromElement{explicit,not a collection join,fetch join,fetch non-lazy 
properties,classAlias=null,role=com...AbstractNewsContent.storesOrigin,tableName=stores_origin,
tableAlias=storesorig1_,origin=news_content abstractne0_,columns={abstractne0_.stores_origin_id,
className=com...StoresOrigin}}] [SELECT new com...ContentStores(news.id, 
news.stores, news.storesOrigin) FROM com...AbstractNewsContent news 
LEFT JOIN FETCH news.storesOrigin WHERE news.storesOrigin.id in :storesOriginIds AND news.createDate >= :startDate]
1
  • 1
    You cannot use joins in projections. Commented Apr 13, 2021 at 15:36

1 Answer 1

1

If you using Spring mark the class as @Transactional, then Spring will handle session management.

@Transactional
public class MyClass {
    ...
}

By using @Transactional, many important aspects such as transaction propagation are handled automatically. In this case if another transactional method is called the method will have the option of joining the ongoing transaction avoiding the "no session" exception.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.