[英]How to properly clone an entity with some modified fields and persist into database?
可以說我有一個這樣的實體,
@Entity(name = "Post")
@Table(name = "post")
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
@OneToMany(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true,
FetchType.LAZY
)
@JsonManagedReference
private List<PostComment> comments = new ArrayList<>();
@OneToOne(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true,
fetch = FetchType.LAZY
)
private PostDetails details;
}
我想克隆這個實體,修改幾個字段,然后將新克隆的實體保存在數據庫中。 實現這一目標的最佳方法是什么?
您可以使用構造函數或構建器模式來使用副本,或者使用簡單的設置器來設置屬性。 然后,使用 EntityManager 的persist()
方法保留新的實體實例。 為避免重復id
值的問題,您不得復制id
字段,而是讓JPA
在實體持久化時生成新的id
。
代碼示例
public class Post {
// constructor, getters and setters are omitted
public Post(Post post) {
//Don’t copy id!
this.title = post.getTitle();
this.comments = new ArrayList<>(post.getComments());
this.details = new PostDetails(post.getDetails());
}
}
public class PostDetails {
// constructor, getters and setters are omitted
public PostDetails(PostDetails details) {
// Don’t copy id!
this.description = details.getDescription();
// copy other fields as needed
}
}
// Usage
public class PostsRepository{
@Autowired
EntityManager em;
public void saveCopy(Post originalPost){
Post clonedPost = new Post(originalPost);
em.persist(clonedPost);
}
}
此外,我強烈建議您編寫測試,以檢查您是否一切正常。 此外,您將有更多的實驗空間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.