The code is correct, except that I just added @DynamicUpdate
to avoid updating unmodified fields, and removed a line which was updating the table from another function.
Why does updating children of a record, remove the connection with its children?
-
22-06-2023 - |
Question
I need to update the items of the following class, although I can update all the items but all fields of the class will be changed to null, and its connection to its members will be removed.
@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;
.....
Hibernate
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();
Example
Before Update
Category
1 2000 Alex Jack 05-05-2014
category_categoryitem
1 137
categoryitem
137 900 20
After Update
category
1 0 Null Null Null
category_categoryitem
categoryitem
137 900 20
Solution 2
OTHER TIPS
Have you tried using @JoinTable
to link Item
and 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>();
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow