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]