转载自简书[spring boot入门——一个懒加载问题]https://www.jianshu.com/p/da5ed794572b
一、这是个问题
情形如下
(1)简单的单元测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class GirlServiceTest {
@Autowired
private GirlService girlService;
@Test
public void findOneTest(){
Girl girl = girlService.findOne(1);
Assert.assertEquals(new Double(500), girl.getSalary());
}
}
(2)简单的service
@Service
public class GirlService {
@Autowired
private GirlRepository repository; //一个继承JpaRepository<Girl, Integer>的类
/**
* 通过id查询一位女生的信息
*/
public Girl findOne(Integer id){
return repository.getOne(id);
}
}
(3)简单的实体类
@Entity
public class Girl {
@Id
@GeneratedValue
private Integer id;
private Double salary;
public Girl() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}
奇怪的错误:
运行测试类型以后,报错
org.hibernate.LazyInitializationException: could not initialize proxy [com.panda.girl.domain.Girl#1] - no Session
……
at com.panda.girl.domain.Girl_$$_jvstbdd_0.getSalary(Girl_$$_jvstbdd_0.java)
at com.panda.girl.GirlServiceTest.findOneTest(GirlServiceTest.java:24)
二、问题虽然解决了
✔(1)在实体类上增加注解@Proxy(lazy = false)
@Entity
@Proxy(lazy = false) //解决懒加载问题
public class Girl {
……
}
✔(2)在测试类报错的方法上增加注解@Transactional
@Test
@Transactional //解决懒加载问题
public void findOneTest(){
Girl girl = girlService.findOne(1);
Assert.assertEquals(new Double(500), girl.getSalary());
}
✔(3)在application.yml配置文件中增加配置
spring:
jpa:
properties:
hibernate:
enable_lazy_load_no_trans: true #解决懒加载问题
三、但是有一些疑问
(1)为什么会出现懒加载的错误?
(2)以上三种解决方法,分别有什么其他影响?利弊如何?
(3)第二种增加事务注解的方法,为什么就能解决懒加载问题?