java - 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 的控制器中工作?
解决方案
但是为什么我必须在 @Test 调用中添加 @Transactional 以及为什么它在没有 @Transactional 的控制器中工作?
Open Session in View (OSIV
) 在应用程序中默认启用Spring Boot
,这可以解释为什么您的生产代码不需要@Transactional
对使用延迟初始化实体的方法进行注释。OSIV
然而,启用有其缺点并且被认为是反模式。
推荐阅读
- r - geom_rect 相当于 vjust 和 hjust
- python - 已安装 python-dev 和 Python.h,但包含错误
- aws-lambda - AWS Lambda 在 DynamoDB 表更改时触发 SNS
- oop - 元表中的 Lua 引用表
- python - 用于非 .com 域的 Python requests.get(url)
- javascript - 使用 Shiny(R) 和 Javascript
- java - 线程对方法的请求计数器
- r - 在循环中使用 prop.table 时从列表中引用变量名
- java - Javafx - 任务“:运行”执行失败
- tfs - 如何报告 TFS 使用情况