Hibernate save object (one to many relationship) foreign key is null

前端 未结 1 1272
后悔当初
后悔当初 2020-12-03 18:14

I have one to many relationships between person class and car class. A person can own many cars and vice versa. I am using restful API to post data. My annotations and Get s

相关标签:
1条回答
  • 2020-12-03 18:48

    This annotation:

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="person")
    

    has two consequences:

    1. mappedBy implies that Car is the owning side of the relationship. This means that whenever you want to establish a relationship between Car and Person, you need to do it by setting the Car.person property to the appropriate value. Changes to Person.cars will be ignored by Hibernate.
    2. cascade=CascadeType.ALL means that whenever you save a Person, Hibernate will also invoke the save operation on all entities contained in Person.cars

    Result: you are calling Session.save() on a bunch of Car entities that do not have the Car.person property set properly.

    Solution: either change the owning side of the relationship (be aware that you will also need a @JoinColumn on Person.cars if you do not want an extra database table to be created) or loop through Person.cars and set the Car.person property properly in each of them.

    cascade=CascadeType.ALL suggests the first solution fits your use case better.

    0 讨论(0)
提交回复
热议问题