下面是JPA实体(使用spring JPA1.9.1.RELEASE和Hibernate 4.3.11.Final)
@Getter @Setter @Entity @Table(name = "product")
class Product {
@Id @GeneratedValue
private Long id;
@Column(name="name")
private String name;
@ManyToMany(cascade = CascadeType.PERSIST)
@JoinTable(
name = "product_attachment",
joinColumns = {
@JoinColumn(name = "product_id", referencedColumnName = "id")
},
inverseJoinColumns = {
@JoinColumn(name = "attachment_id", referencedColumnName = "id")
}
)
private List<Attachment> attachments;
}我需要克隆product和product_attachment列。(不是attachment,所以它是主表)
private Product _clone(Product src) {
Product dst = new Product();
BeanUtils.copyProperties(src, dst, "id", "attachments");
dst.setAttachments(src.getAttachments());
return productRepository.save(dst);
}但我不例外。
org.hibernate.HibernateException: Found shared references to a collection: Product.attachments
我解决这个问题的方法是再次获得相同的实体。密码在下面。
private Product _clone(Product src) {
Product dst = new Product();
BeanUtils.copyProperties(src, dst, "id", "attachments");
dst.setAttachments(
attachmentRepository.findAll(
src.getAttachments().stream()
.map(Attachment::getId).collect(Collectors.toList())
)
);
return productRepository.save(dst);
}但这似乎是多余的,谁知道更好的方法?
发布于 2016-01-15 07:39:04
您不能克隆集合attachments itselfe,而必须复制其内容。(我认为原因是Hibernate使用一些黑客来检测集合内容上的更改)。
dst.attachments = new ArrayList(src.attachments);发布于 2016-01-15 07:49:47
问题是,复制的列表引用了源产品(浅)中的附件。
您应该使用与手动复制Product相同的方法复制附件条目:
Product dst = new Product();
BeanUtils.copyProperties(src, dst, "id", "attachments");
dst.setAttachments(new ArrayList<Attachment>(src.getAttachments().size()));
for(Attachment a : src.getAttachments()){
Attachment dstA = new Attachment();
BeanUtils.copyProperties(a, dstA, {Your properties});
a.getAttachments().add(dstA);
}或者您可以使用帮助类,如Apache方法来执行源产品的深度复制。
https://stackoverflow.com/questions/34804693
复制相似问题