簡體   English   中英

spring-data-jpa,克隆ManyToMany映射表

[英]spring-data-jpa, to clone ManyToMany mapping table

我在JPA實體下面(使用spring-data-jpa 1.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;
}

我需要克隆productproduct_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);
}

但這似乎是多余的,有人知道更好的方法嗎?

您不能克隆集合attachments本身,而必須復制其內容。 (我認為原因是Hibernate使用一些技巧來檢測集合內容上的更改)。

 dst.attachments = new ArrayList(src.attachments);

問題在於您的復制列表引用了源產品(淺)中的附件。

您應該使用與手動復制產品相同的方法復制附件條目:

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 Commons SerializationUtils.clone()方法之類的幫助程序類來執行源產品的深層副本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM