单向OneToMany JPA仍然存在

时间:2015-02-01 22:37:49

标签: java jpa

我在JPA中使用单向OneToMany关系时有一些奇怪的行为。 这是我的模特:



Entity
@Table(name = "PRODUCTS")
public class Product implements Serializable {

    @Column(name = "PRODUCT_ID_PK")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long oid;

    @OneToMany(cascade={CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
    @JoinColumn(name = "PRODUCT_ID_FK", referencedColumnName = "PRODUCT_ID_PK")
    private List<Attribute> attributes;

  
    @OneToMany(orphanRemoval = true,cascade={CascadeType.ALL})
    @JoinColumn(name = "PRODUCT_ID_FK", referencedColumnName = "PRODUCT_ID_PK")
    private List<Price> prices;
}

@Entity
@Table(name = "ATTRIBUTES")
public class Attribute implements Serializable {

    @Column(name = "ATTRIBUTE_ID_PK")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int oid;

    private String name;
}

@Entity
@Table(name = "PRICES")
public class Price implements Serializable {

    @Column(name = "PRICE_ID_PK")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int oid;

    private int value;
}
&#13;
&#13;
&#13;

我创建了一个&#34;产品&#34;并在db。中保留产品。

后来我想添加一些属性。

这是执行此操作的代码:

&#13;
&#13;
  //start transaction
  for (SomeElement el: someElements) {
        Attribute attr = new Attribute(el);
        product.getAttributes().addAttribute(attr);
   }

   for (SomeOtherElement el: someOtherElements) {
         Price price = new Price(el);
         product.getPrices().addPrice(price);
   }
   product = em.merge(product);
   em.flush();
   ...
   //end transaction
&#13;
&#13;
&#13;

代码不会报告任何错误,但只会添加每个集合的第一个元素。这是正确的行为吗? 添加整个元素集合的建议方法是什么?

提前致谢 VR

0 个答案:

没有答案