spring数据jpa没有插入db

20jt8wwn  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(256)

**结束。**此问题需要详细的调试信息。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

5天前关门了。
改进这个问题

@Entity
public class Posts {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
}
@Entity
@Data
public class PostsDetail {

  @Id
  private Long id;

  @OneToOne(fetch = FetchType.LAZY)
  @MapsId
  private Posts posts;

}

这是一个非常简单的共享密钥jpa代码。

@Test
  void t1() {
    Posts posts = new Posts();
    Posts save = postsRepository.save(posts);

    PostsDetail postsDetail = new PostsDetail();
    postsDetail.setPosts(save);
    postsDetailRepository.save(postsDetail);
  }

它有错误
error msg=传递给持久化的分离实体嵌套异常为org.hibernate.persistentobjectexception:传递给持久化的分离实体

w1e3prcc

w1e3prcc1#

我认为你的情况与这里所描述的相似。请注意,如果父实体尚未保存,则必须将其从从属实体中保存 PostsDetail . 所以,如果你做了以下几点就可以了:

Posts posts = new Posts(); 
//Posts savedPost = postsRepository.save(posts); // <-- here
PostsDetail postsDetail = new PostsDetail();
postsDetail.setPosts(posts); // <-- here
postsDetailRepository.save(postsDetail);

save() 不会立即刷新数据, savedPost 当你这样做的时候,你不会坚持 postsDetailRepository.save(postsDetail);

相关问题