我有 2 個物體與 OneToMany 的關系
@Entity
class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", insertable = false, updatable = false)
private Long id;
@OneToMany(mappedBy = "post", fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
Set<Comment> comments = new HashSet();
public void addComment(Comment c) {
c.setPost(this);
comments.add(c);
}
}
@Entity
class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", insertable = false, updatable = false)
private Long id;
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;
}
CREATE TABLE post(
id BIGINT NOT NULL DEFAULT nextval('post_id_seq') PRIMARY KEY,
title VARCHAR(50)
);
CREATE TABLE comment (
id BIGINT NOT NULL PRIMARY KEY,
post_id BIGINT NOT NULL,
text VARCHAR(255),
CONSTRAINT fk_comment_post_id
FOREIGN KEY (post_id)
REFERENCES post (id)
);
當保存此物體時,一切正常,而savedPost是一個包含評論的完整物體。
Post post = new Post();
post.setId(1L);
post.setTitle("Hello post test");
post.addComment(new Comment("Hi There");
Post savedPost = postRepository.save(post);
但是,從我決定洗掉該序列以在 Post 表中生成 Post Id 并洗掉注釋 @GenerateValue 并使用我生成的數字設定 id 的那一刻起,事情開始下降
CREATE TABLE post(
id BIGINT NOT NULL PRIMARY KEY,
title VARCHAR(50)
);
@Entity
class Post {
@Id
@Column(name = "id", updatable = false)
private Long id;
...
}
現在保存帖子后,savedPost物件不再包含評論(實際上它包含一個所有欄位為空的評論)。似乎連接被破壞了。
知道它在哪里以及為什么發生嗎?
更新基于 Simon Martinelli 的代碼:github.com/simasch/69978943
If instead of .save(post) I call .saveAndFlush(post) the comment returns with ONLY its ID set, the rest of the fields come null. It is better than the behavior I describe, but still not good.
But if I annotate Post.id with @GeneratedValue and use.save(post), everything works perfectly.
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false)
private Long id;
uj5u.com熱心網友回復:
問題可以在SimpleJpaRepository save()方法中找到
@Transactional
@Override
public <S extends T> S save(S entity) {
Assert.notNull(entity, "Entity must not be null.");
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
在那里檢查物體是否是新的。但是當你手動設定ID它不被視為新的,為此沒有EntityManger.persist(),但EntityManager.merge()被呼叫。
所以你需要將 CascadeType.MERGE 添加到映射中
@OneToMany(mappedBy = "post", fetch = FetchType.EAGER,
cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private Set<Comment> comments = new HashSet<>();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/358236.html
標籤:hibernate jpa spring-data-jpa one-to-many many-to-one
