0
@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.

Daud
  • 7,429
  • 18
  • 68
  • 115
  • You should save your car instances first after setting their persons. – Sotirios Delimanolis Mar 13 '13 at 15:44
  • @SotiriosDelimanolis But the car instances will be automatically saved when we save the Person entity... which is happening correctly.. my question is why do we need to save cars first.. to get the correct mapping ? – Daud Mar 13 '13 at 16:05
  • It did not work even when we saved the car instances first – Daud Mar 13 '13 at 16:06

2 Answers2

1

Try calling car.setPerson(per).

Derek
  • 749
  • 1
  • 7
  • 19
  • It worked when I set the person object on both the car objects... but why did my way of doing it not work ? – Daud Mar 13 '13 at 16:10
  • That's how Hibernate works. I don't have link to docs right now, but try googling it. – Sotirios Delimanolis Mar 13 '13 at 16:18
  • 1
    I don't have a good answer either, seems I might not be the only one: http://stackoverflow.com/questions/2921314/hibernate-annotated-many-to-one-not-adding-child-to-parent-collection – Derek Mar 13 '13 at 16:39
1

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!

overmeulen
  • 1,158
  • 6
  • 15
  • The cars are in fact, getting saved. But why is the person_id being null ? – Daud Mar 13 '13 at 16:39
  • 1
    The cars are being saved thanks to the CascadeType.ALL you specified in your OneToMany but the foreign key is not correctly filled because you assume that the owner of the relation is Person whereas with your mapping it is Car. – overmeulen Mar 13 '13 at 16:52