【发布时间】:2020-08-17 16:17:43
【问题描述】:
我有一个简单直接的演示应用程序,其中包含 spring-boot、spring-data-jpa 和 h2-DB。
我已经构建了两个由OneToOne 关系映射的实体。
Post.java
@Entity
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
@OneToOne(mappedBy = "post", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private PostDetail postDetail;
}
PostDetail.java
@Entity
public class PostDetail {
@Id
@GeneratedValue
private Long id;
private String message;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JoinColumn(name = "id")
private Post post;
}
我尝试创建并保存一个新的Post。然后我尝试新建一个PostDetail,将之前生成的Post设置为它并保存。在一个控制器示例中,我没有 @Transactional 注释,而在第二个示例中,我使用 @Transactional 注释方法
@RestController
public class TestController {
@Autowired
PostRepository postRepository;
@Autowired
PostDetailRepository postDetailRepository;
@GetMapping("/test1")
public String test1() {
Post post = new Post();
post.setId(2L);
post.setTitle("Post 1");
postRepository.save(post);
PostDetail detail = new PostDetail();
detail.setMessage("Detail 1");
detail.setPost(post);
postDetailRepository.save(detail);
return "";
}
@Transactional
@GetMapping("/test2")
public String test2() {
Post post = new Post();
post.setId(2L);
post.setTitle("Post 1");
postRepository.save(post);
PostDetail detail = new PostDetail();
detail.setMessage("Detail 1");
detail.setPost(post);
postDetailRepository.save(detail);
return "";
}
}
为什么我在第一个示例中得到 org.hibernate.PersistentObjectException: detached entity passed to persist: com.example.demo.jpa.model.Post 异常而在另一个示例中没有?
谁能解释为什么会这样?
【问题讨论】:
标签: spring spring-boot hibernate jpa spring-data-jpa