'Spring: Not-null property references a null or transient value
I have an entity(Car) and i want to add records belong this entity with postman. My entity has one relational connection with User entity.
When i want to add a Car object to database, i get an error :
message=not-null property references a null or transient value : com.carnft.carr.entity.Car.user;
This is the entity that i want to add from postman:
@Entity
@Table(name = "car")
@Data
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonView(Views.Base.class)
private String name;
@JsonView(Views.Base.class)
private String qtype;
@JsonView(Views.Base.class)
private int km;
@JsonView(Views.Base.class)
private String image;
private boolean sellStatus=false;
@ManyToOne(fetch = FetchType.LAZY,cascade = {CascadeType.ALL})
@JoinColumn(name="user_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
User user;
}
And this is the method inside Car controller:
@PostMapping
public Car addCar(@RequestBody Car car){
return carService.addCar(car);
}
And this is the service:
public Car addCar(Car car) {
return carRepository.save(car);
}
I neither add any car with postman or directly from mysql workbench.
Solution 1:[1]
Your attribute User user
in Car
entity has the annotation @JoinColumn(name="user_id", nullable = false)
which force user
to not be null.
When you save your Car
entity, you must set a user
entity to it with car.setUser(yourUserEntity)
.
For now, your method addCar
only save a car
with carRepository.save(car);
Or you can remove nullable = false
from your annotation.
Solution 2:[2]
I had the same problem long ago. You need to manually install lombok on your device or remove lombok and use getter and setter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pilpo |
Solution 2 | Chekwube Alaekwe |