持久化的时候使用JPA ,使用merge处理父子表数据的时候,注释类配置如下
父entity 类的子entity配置如下
/**
* 获取附件列表
*
* @return the articleAttachments
*/
@Valid
@OneToMany(mappedBy = "article", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@ElementCollection(targetClass = ArticleAttachment.class, fetch = FetchType.LAZY)
@CollectionTable(name = "xx_article_attachment", joinColumns = @JoinColumn(name = "article", referencedColumnName = "id"))
@OrderBy("priority asc")
public List<ArticleAttachment> getArticleAttachments() {
return articleAttachments;
}
使用了@OneToMany and CASCADE.ALL
这个时候执行merge操作的时候,会出现字表数据重复插入2次的问题,在JBoss hibernate官网我找到了bug fix JBoss的东西都挺重的。
修改成@OneToMany and CASCADE.PERSIST,申明为级联级联保存
/**
* 获取附件列表
*
* @return the articleAttachments
*/
@Valid
@OneToMany(mappedBy = "article", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@ElementCollection(targetClass = ArticleAttachment.class, fetch = FetchType.LAZY)
@CollectionTable(name = "xx_article_attachment", joinColumns = @JoinColumn(name = "article", referencedColumnName = "id"))
@OrderBy("priority asc")
public List<ArticleAttachment> getArticleAttachments() {
return articleAttachments;
}
【FAQ Fix】 JPA Double insert with @OneToMany and CASCADE.ALL,布布扣,bubuko.com