Hibernate OneToMany 关系在插入实体时将外键设置为空
Hibernate OneToMany relationship sets foreign key to null when inserting entity
我有两个实体:人物和事件。这个想法是一个人是几个事件的所有者,一个事件只能由一个人拥有。
人物实体片段:
@OneToMany(fetch = FetchType.EAGER,cascade=CascadeType.ALL,mappedBy="person")
@JsonIgnore
private List<Event> event;
事件实体片段:
@ManyToOne(fetch=FetchType.EAGER, cascade={CascadeType.PERSIST, CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH})
@JsonIgnore
private Person person;
当我尝试插入一个人并随后在数据库中向其添加一些事件时,事件 table 中的外键始终为空。这意味着我无法跟踪事件的 "owner"(这是我的目标)。
此外,如果我想使用 @JoinTable 注释来跟踪所有者,我应该怎么做?
欢迎任何建议。
可能您没有正确连接实体。以下伪代码将向您展示如何连接实体:
Person person = new Person();
Event event1 = new Event();
Event event2 = new Event();
person.getEvents().add(event1);
person.getEvents().add(event2);
event1.setPerson(person);
event2.setPerson(person);
// Start transaction here
entityManager.persist(person); // this should save also events because of cascade attribute
// commit transaction
Moreover, if I wanted to use a @JoinTable annotation instead to keep track of the owner how should I do that?
在你的情况下,你不需要它,因为你有双向关系。仅当您具有从 Person
到 Event
.
的单向 @OneToMany
关系时,这才有意义
我有两个实体:人物和事件。这个想法是一个人是几个事件的所有者,一个事件只能由一个人拥有。
人物实体片段:
@OneToMany(fetch = FetchType.EAGER,cascade=CascadeType.ALL,mappedBy="person")
@JsonIgnore
private List<Event> event;
事件实体片段:
@ManyToOne(fetch=FetchType.EAGER, cascade={CascadeType.PERSIST, CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH})
@JsonIgnore
private Person person;
当我尝试插入一个人并随后在数据库中向其添加一些事件时,事件 table 中的外键始终为空。这意味着我无法跟踪事件的 "owner"(这是我的目标)。
此外,如果我想使用 @JoinTable 注释来跟踪所有者,我应该怎么做?
欢迎任何建议。
可能您没有正确连接实体。以下伪代码将向您展示如何连接实体:
Person person = new Person();
Event event1 = new Event();
Event event2 = new Event();
person.getEvents().add(event1);
person.getEvents().add(event2);
event1.setPerson(person);
event2.setPerson(person);
// Start transaction here
entityManager.persist(person); // this should save also events because of cascade attribute
// commit transaction
Moreover, if I wanted to use a @JoinTable annotation instead to keep track of the owner how should I do that?
在你的情况下,你不需要它,因为你有双向关系。仅当您具有从 Person
到 Event
.
@OneToMany
关系时,这才有意义