我需要更新以下类的项目,虽然我可以更新所有项目但是该类的所有字段都将更改为null,并且将删除它与其成员的连接。
@Entity
public class Category implements Serializable {
@Id
@GeneratedValue
private long id;
@OneToMany( cascade = CascadeType.ALL, orphanRemoval = true)
@LazyCollection(LazyCollectionOption.FALSE)
private List<Items> items;
private float price;
@ManyToOne
private Staff user;
@ManyToOne
private Staff owner;
@Temporal(javax.persistence.TemporalType.DATE)
private Date createDate;
....
@Entity
public class Items {
@Id
@GeneratedValue
private Long id;
private int serial;
@OneToOne
private Product product;
.....
休眠
Category cat = (Category) session.get(Category.class, id);
for (int i = 0; i < cat.getItems().size(); i++) {
cat.getItems().get(i).getProduct().setQuantity(10);
Part part = new Part();
part.setName("Temp");
cat.getItems().get(i).getProduct().getPart.add(part);
session.update(cat.getItems().get(i).getProduct());
session.save(part);
}
tx.commit();
示例
更新前
Category
1 2000 Alex Jack 05-05-2014
category_categoryitem
1 137
categoryitem
137 900 20
更新后
category
1 0 Null Null Null
category_categoryitem
categoryitem
137 900 20
答案 0 :(得分:1)
您是否尝试过使用@JoinTable
关联Item
和Category
?
Category.java
...
@OneoMany(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(
name="category_items",
joinColumns={@JoinColumn(name="category", referencedColumnName="id")},
inverseJoinColumns={@JoinColumn(name="item", referencedColumnName="id")})
private Set<Items> items = new HashSet<Items>();
...
答案 1 :(得分:0)
代码是正确的,除了我刚刚添加@DynamicUpdate
以避免更新未修改的字段,并删除了从另一个函数更新表的行。