webpersistence
webpersistence

Reputation: 904

JPA Cascade Persistence

I want to store Persons with their Cars in the database. I use Spring 5.

The problem is that when I want to add a person with cars in the database, the 'person_id' field from the 'car' table is set to null instead of being set on the id of the created person. That is weird because I even set that nullable=false in Car class.

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    @OneToMany(mappedBy = "person",cascade = CascadeType.ALL)
    List<Car> cars;

}

@Entity
public class Car {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer carId;

    @ManyToOne
    @JoinColumn(name = "person_id",nullable=false)
    private Person person;
}



CREATE TABLE person (
    id INT PRIMARY KEY AUTO_INCREMENT,
    ...
);

CREATE TABLE car (
    id INT PRIMARY KEY AUTO_INCREMENT,
    person_id INT,
    ADD CONSTRAINT person_id REFERENCES person(id)
);

I use the JpaRepository to save a person:

Person p = new Person();
List<Car> cars = new ArrayList<>();
Car c1 = new Car();
Car c2 = new Car();

cars.add(c1);
cars.add(c2);
p.setCars(cars);
personJpaRepository.save(p); 

Upvotes: 2

Views: 156

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26492

If you want to take advantage of the Cascade option you must remember to set the dependencies on both sides of the relationship. Otherwise the persistence provider will not consider that as a relationship:

cars.add(c1);
cars.add(c2);

c1.setPerson(p);
c2.setPerson(p);

p.setCars(cars);
personJpaRepository.save(p); 

Upvotes: 1

Related Questions