Ich möchte Personen mit ihren Autos in der Datenbank speichern. Ich benutze Frühling 5.JPA Cascade Persistence
Das Problem ist, dass, wenn ich Person mit Autos in der Datenbank hinzufügen möchte, das Feld 'person_id' aus der 'Auto'-Tabelle auf Null gesetzt wird anstatt auf die ID des Erstellten gesetzt Person. Das ist komisch, weil ich sogar nullable=false
in der Car-Klasse gesetzt habe.
@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)
);
Ich benutze die JpaRepository
eine Person zu retten:
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);
Sie das Auto nicht auf die Person –
Vorschlag halten Mapping und db synchron hinzugefügt haben: in eine nicht null auf person_id – Zeromus