Reputation: 7887
@Entity
public class Person implements Serializable{
@Id
@GeneratedValue
private int id;
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "person")
private List<Car> cars;
//getters and setters
}
@Entity
public class Car implements Serializable{
@Id
@GeneratedValue
private int id;
private String name;
@ManyToOne
@JoinColumn(name = "person_id")
private Person person;
// getters and setters
}
And.. I use it thus..
Person per = new Person();
per.setName("some");
Car car1 = new Car();
car1.setName("Ford");
Car car2 = new Car();
car2.setName("WagonR");
//s.save(car1);
//s.save(car2);
per.setCars(new ArrayList<Car>());
per.getCars().add(car1);
per.getCars().add(car2);
s.save(per);
Now.. the table Car
has a column person_id
but its showing null
for both the cars.. what am I doing wrong here ? The table Person
is correctly being filled. If I remove the "mappedBy
" from the Person
table.. and instead include the @JoinColumn
here... then it works fine.
Upvotes: 0
Views: 193
Reputation: 1158
With your mapping, the owner of the relation is the Car and not the Person ... That's why when saving the Person, the Car is not saved. If you remove the mappedBy
then the owner of the relation becomes the Person and you get your expected behavior!
Upvotes: 1