Reputation: 959
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:
@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?
Upvotes: 1
Views: 945
Reputation: 48133
Do the opposite, set a Room
as the room field of a Person
instance:
Room room = ...;
person.setRoom(room);
// persist the person
With the mappedBy
, you specify that which entity owns the relationship. 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.
Upvotes: 2
Reputation: 8247
You need to set CascadeType=PERSIST or ALL
on @OneToMany
. And Also set room
variable in Person
class to populate foreign key in Person table.
Upvotes: 2