解决JPA延迟加载no Session报错

本文介绍了三种解决Spring Boot中JPA延迟加载时遇到的'no Session'错误的方法。第一种是在application.yml配置文件中设置spring.jpa.open-in-view为true,并在查询方法上添加@Transactional注解。第二种方法是将懒加载转换为急加载。第三种方法是在启动类中添加拦截器,但可能需要降级Spring Boot版本才能生效。
摘要由CSDN通过智能技术生成

springboot解决JPA延迟加载no Session报错

第一种
参考链接

在application.yml中添加spring.jpa.open-in-view: true
在这里插入图片描述

  jpa:
    database: mysql
    #报错:Error executing DDL,解决方案:设置数据库引擎为InnoDB
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    #自动创建并修改表结构
    #create 启动时删数据库中的表,然后创建,退出时不删除数据表
    #create-drop 启动时删数据库中的表,然后创建࿰
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值