Background
I have an Car entity with a @ManyToOne relationship with a Make entity:
@Entity
public class Car {
@Id
Long id;
@ManyToOne(cascade = CascadeType.ALL)
Make make;
}
@Entity
public class Make {
@Id
Long id;
String name;
}
Both Car and Make have repositories:
public interface CarRepository extends CrudRepository<Car, Long> {
}
public interface MakeRepository extends CrudRepository<Make, Long> {
}
Problem
When a client issues an HTTP POST request to the Spring Data REST endpoint /api/cars with a payload of:
{
"id":null,
"make": {
"id": null,
"name": "Toyota"
}
}
A new car is created and persisted in the database but its Make is set as null in the DB.
What I expected
Since CascadeType.ALL is specified and the make of the car has a null id, I thought a new Make record would be persisted in the DB and that the new Car record would have its foreign key to Make (i.e., makeId) set to that new Make record.
Observations
- If
Makedoes not have its own repository (i.e., I delete theMakeRepository), the make will be persisted as expected and associated with the new car. - If I annotate the
makefield inCarwith@RestResource(exported = false), the make will be persisted as expected and associated with the new car. - If I save
Makefirst and then set that on theCar, the make will obviously be persisted and then associated with the new car.
Questions
Is there a way to save the make of a car without adding @RestResource to the make field or without a separate save? Where can I find Spring documentation describing this behavior?
Why Make (i.e., makeId) is set as null in the DB :
How we can fix / solve :
Update your entity like below
@Entity public class Car {
}
@Entity public class Make {
}
To save a new Car and a new Make with a single save ie
carRepository.save(car)your payload will be like belowcarRepository.save(car)your payload will be like below