Jpa的实体配置懒加载后no session or session was closed问题解决

实体配置如下:

解放办法如下:

第一种办法(在 Repository 里面设置,使用 JOIN FETCH

public interface IndicatorRepository extends BaseRepository<Indicator, String> {

    @Query(value = "SELECT p FROM Indicator p JOIN FETCH p.indicatorCategory where p.id = ?1")
    Indicator fetchIndicatorCategory(String id);
    
}

第二种办法(使用 Hibernate.initialize(Object)

    public IndicatorGroupTree findByIdFetchParent(String id) {
        return indicatorGroupTreeRepository.findById(id)
                .map(o -> {
                    Hibernate.initialize(o.getParent());
                    return o;
                }).orElse(null);
    }

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在多线程环境下,如果使用JPA懒加载机制,可能会出现“No session”错误。这是因为每个线程都有自己的事务和Session,当一个线程查询到一个懒加载属性时,它会尝试从自己的Session加载该属性,但是由于该Session已经关闭了,就会出现“No session”错误。 解决问题的方法有两种: 1. 使用EAGER加载方式替代懒加载懒加载属性改为EAGER加载方式,这样在查询主实体时就会同时查询加载所有关联实体的数据,避免了在后续使用时出现“No session”错误。但是这种方式可能会导致性能问题,因为EAGER加载会一次性加载所有关联实体的数据,如果关联实体数据量很大,可能会导致查询性能下降。 2. 在每个线程中重新打开Session 在每个线程中重新打开Session,这样就可以保证每个线程都能访问到自己的Session,避免了“No session”错误。可以使用ThreadLocal来保存每个线程的Session,保证线程安全。示例代码如下: ``` public class JpaUtil { private static ThreadLocal<EntityManager> threadLocal = new ThreadLocal<>(); public static EntityManager getEntityManager() { EntityManager entityManager = threadLocal.get(); if (entityManager == null) { entityManager = EntityManagerFactoryHolder.getEntityManagerFactory().createEntityManager(); threadLocal.set(entityManager); } return entityManager; } public static void closeEntityManager() { EntityManager entityManager = threadLocal.get(); if (entityManager != null) { entityManager.close(); threadLocal.remove(); } } } ``` 使用时,在每个线程中打开和关闭Session: ``` public void doInNewThread() { JpaUtil.getEntityManager().getTransaction().begin(); // 查询主实体,关联实体使用懒加载 MainEntity mainEntity = JpaUtil.getEntityManager().find(MainEntity.class, 1L); // 加载关联实体 Hibernate.initialize(mainEntity.getLazyEntity()); JpaUtil.getEntityManager().getTransaction().commit(); JpaUtil.closeEntityManager(); } ``` 这样就可以在多线程环境下使用JPA懒加载机制了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值