我正在学习 Hibernate(v. 6.6.1 Final)并且遇到问题
人
@Entity
@Table(name = "person")
public class Person {
@Id
@Column(name = "id")
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "java_seq_generator_person"
)
@SequenceGenerator(
name = "java_seq_generator_person",
sequenceName = "person_id_sequence",
allocationSize = 1
)
private int id;
@Column(name = "name",nullable = false)
private String name;
@Column(name = "age")
private int age;
@OneToMany(mappedBy = "owner", cascade = CascadeType.PERSIST)
private List<Item> items;
// save item method
public void saveItem(Item item) {
if (this.items == null) {
this.items = new ArrayList<>();
}
item.setOwner(this);
this.items.add(item);
}
// constructors, getters and setters
}
项目
@Entity
@Table(name = "Item")
public class Item {
@Id
@Column(name = "id")
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "java_seq_generator_item"
)
@SequenceGenerator(
name = "java_seq_generator_item",
sequenceName = "item_id_sequence",
allocationSize = 1
)
private int id;
@ManyToOne
@JoinColumn(name = "person_id", referencedColumnName = "id")
private Person owner;
@Column(name = "item_name", nullable = false)
private String itemName;
// constructors, getters and setters
...
}
Person 表中的一条记录 { ID:13, name: “测试者”, 年龄:77 }
然后我从数据库中获取这个人 - >创建新项目 - >并将该项目添加到我的人中,但是hibernate仅生成从数据库获取人的SELECT sql查询,并且没有子项目的INSERT查询;
session.beginTransaction();
Person person = session.get(Person.class, 13);
Item item = new Item("TEST item");
person.saveItem(item);
session.getTransaction().commit();
我不明白为什么,因为当我从数据库(持久/托管状态)获取对象(人),并为子设置 CascadeType 时;我认为 Hibernate 会自动保存我的子项目,导致对象人发生变化;
所以我的问题是为什么我的子项目没有保存以及如何正确配置它以在父项目更改时保存子项目?
因为您正在对 Person
对象执行
MERGE操作,并且您仅为 PERSIST 操作启用了级联。 添加
CascadeType.MERGE
即可解决问题。
@OneToMany(mappedBy = "owner", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private List<Item> items;