简体   繁体   English

JPA映射不保留具有关系的实体

[英]JPA mappedBy don't persisting entity with relationship

For example, I have the following entities: Room entity: 例如,我有以下实体:房间实体:

@Entity
public class Room extends Base {

@OneToMany(mappedBy = "room")
private List<Person> persons;
//getters and setters
}

And the Person entity: 和Person实体:

@Entity
public class Person extends Base {

@ManyToOne
private Room room;

private String name;
//getters and setters
}

If I add person to room's persons list and then persist, the room is added, but person is not. 如果我将某人添加到会议室的人员列表中,然后坚持执行,则会添加会议室,但不会添加人员。 I thought, enough is to add mappedBy parameter to OneToMany annotation, but.. what should I do else? 我认为,足以将mappedBy参数添加到OneToMany批注中,但是..我还应该怎么办?

You need to set CascadeType=PERSIST or ALL on @OneToMany . 您需要在@OneToMany上设置CascadeType=PERSIST or ALL And Also set room variable in Person class to populate foreign key in Person table. 并且还要在Person类中设置room变量以填充Person表中的外键。

Do the opposite, set a Room as the room field of a Person instance: 相反,将Room设置为Person实例的room字段:

Room room = ...;
person.setRoom(room);
// persist the person  

With the mappedBy , you specify that which entity owns the relationship . 使用mappedBy ,您可以指定哪个实体拥有该关系 Updating the relationship between those two entities is the responsibility of the owning side . 更新这两个实体之间的关系是拥有方的责任

In your example, the Person owns the relationship, so it's his responsibility to update the foreign key, not Room 's, so when you add a Person to list of persons in Room and update the Room , Room wouldn't update the foreign key for you. 在您的示例中,该Person拥有该关系,因此更新外键(而不是Room )是他的责任,因此当您将一个Person添加到RoomPerson列表并更新RoomRoom不会更新外键为了你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM