首页 > 解决方案 > JUnit hibernate.LazyInitializationException

问题描述

我有一对多双向的简单示例。

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@Data
@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String title;
    private String description;
    private Date createDate;
    private int rate;

    @ToString.Exclude
    @OneToMany(mappedBy = "post",cascade = CascadeType.ALL)
    List<Comment> comments=new ArrayList<>();
}

.

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@Data
@Entity
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String text;

    @JsonIgnore
    @ManyToOne
    private Post post;

}

当我打电话时

@GetMapping("post/{id}")
public Post getPost(@PathVariable Long id) {
    return postRepository.getOne(id);
}

在此处输入图像描述

一切都好但是我让@Test

@Test
void getPost() {
    Post post = postRepository.getOne(1L);
    System.out.println(post);
}

我有错误

org.hibernate.LazyInitializationException: could not initialize proxy [ge.cse.jpademo.model.Post#1] - no Session

在此处输入图像描述

我该如何解决这个问题?

我尝试添加@Transactional 注释及其作品。

@Transactional
@Test
void getPost() {
    Post post = postRepository.getOne(1L);
    System.out.println(post);
}

.

Post(id=1, title=სატესტო პოსტი3, description=სატესტო კონტენტი, createDate=2020-05-19 02:26:16.237, rate=5)

但是为什么我必须在 @Test 调用中添加 @Transactional 以及为什么它在没有 @Transactional 的控制器中工作?

标签: javajunit

解决方案


但是为什么我必须在 @Test 调用中添加 @Transactional 以及为什么它在没有 @Transactional 的控制器中工作?

Open Session in View (OSIV) 在应用程序中默认启用Spring Boot,这可以解释为什么您的生产代码不需要@Transactional对使用延迟初始化实体的方法进行注释。OSIV然而,启用有其缺点并且被认为是反模式


推荐阅读