我的存储库中有以下读取方法
@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);
它产生org.hibernate.LazyInitializationException: could not initialize proxy [com...StoresOrigin#592] - no Session
好的,这是因为字段的惰性初始化(这是所需的行为)
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "STORES_ORIGIN_ID")
protected StoresOrigin storesOrigin;
然后我读了更多关于如何解决这个问题的内容,我添加了“LEFT JOIN FETCH news.storesOrigin”,它看起来像:
@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);
在构建项目时,我得到了以下信息:
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条答案
按热度按时间ufj5ltwl1#
如果您使用Spring将类标记为@Transactional,则Spring将处理会话管理。
通过使用@Transactional,许多重要的方面(如事务传播)都可以自动处理。在这种情况下,如果调用了另一个事务方法,该方法将可以选择加入正在进行的事务,从而避免出现“无会话”异常。