У меня есть два класса User.java
и Vehicle.java
с отношением OneToMany
. Когда я отправляю через почтальона пользователя с 2 автомобилями, данные правильно хранятся в базе данных, но внешний ключ в таблице транспортных средств всегда сохраняется как null
.
User.java
@Entity
@Table(name = "users", schema = "vehicleproject")
public class User {
@Id
@Column(name = "user_id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "email")
private String email;
@Column(name = "password")
private String password;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "address")
private String address;
@Column(name = "afm")
private int afm;
@Column(name = "role_id")
private UserType type;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Vehicle> vehicles = new ArrayList<>();
public User(){}
public User(long id, String email, String password, String firstName, String lastName, String address, int afm, UserType type, List<Vehicle> vehicles) {
this.id = id;
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.afm = afm;
this.type = type;
this.vehicles = vehicles;
}
public User(long id, String email, String password, String firstName, String lastName, String address, int afm, UserType type) {
this.id = id;
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.afm = afm;
this.type = type;
this.vehicles = new ArrayList<>();
}
public User(String email, String password, String firstName, String lastName, String address, int afm, UserType type, List<Vehicle> vehicles) {
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.afm = afm;
this.type = type;
this.vehicles = vehicles;
}
public List<Vehicle> getVehicles() {
return vehicles;
}
public void setVehicles(List<Vehicle> vehicles) {
this.vehicles = vehicles;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAfm() {
return afm;
}
public void setAfm(int afm) {
this.afm = afm;
}
public UserType getType() {
return type;
}
public void setType(UserType type) {
this.type = type;
}
public void addVehicleToList(Vehicle vehicle){
this.vehicles.add(vehicle);
}
public void removeVehicleFromUserList(Vehicle vehicle){
this.vehicles.remove(vehicle);
}
}
Vehicle.java
@Entity
@Table(name = "vehicles", schema = "vehicleproject")
public class Vehicle {
@Id
@Column(name = "vehicle_id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "brand")
private String brand;
@Column(name = "model")
private String model;
@Column(name = "creation_date")
private LocalDate creationDate;
@Column(name = "color")
private String color;
@JsonIgnore
@ManyToOne
@JoinColumn(name = "user_id", referencedColumnName = "user_id")
private User user;
@Column(name = "plate_number")
private String plateNumber;
public Vehicle(){
}
public Vehicle(long id, String brand, String model, LocalDate creationDate, String color, User user, String plateNumber) {
this.id = id;
this.brand = brand;
this.model = model;
this.creationDate = creationDate;
this.color = color;
this.user = user;
this.plateNumber = plateNumber;
}
public Vehicle(String brand, String model, LocalDate creationDate, String color, User user, String plateNumber) {
this.brand = brand;
this.model = model;
this.creationDate = creationDate;
this.color = color;
this.user = user;
this.plateNumber = plateNumber;
}
public Vehicle(long id, String brand, String model, LocalDate creationDate, String color, String plateNumber) {
this.id = id;
this.brand = brand;
this.model = model;
this.creationDate = creationDate;
this.color = color;
this.plateNumber = plateNumber;
}
public String getPlateNumber() {
return plateNumber;
}
public void setPlateNumber(String plateNumber) {
this.plateNumber = plateNumber;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public LocalDate getCreationDate() {
return creationDate;
}
public void setCreationDate(LocalDate creationDate) {
this.creationDate = creationDate;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@JsonIgnore
public User getUser() {
return user;
}
@JsonProperty
public void setUser(User user) {
this.user = user;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vehicle vehicle = (Vehicle) o;
return id == vehicle.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
Моя json
полезная нагрузка:
{
"email": "new@player7.com",
"password": "newplayer2",
"firstName": "ithList",
"lastName": "Constructor",
"address": "Ermou 20",
"afm": 1005733537,
"type": "USER",
"vehicles": [
{
"brand": "MASSERATI",
"model": "GOD",
"creationDate": "2015-05-05",
"color": "WHITE",
"plateNumber": "Amm2421"
},
{
"brand": "Toyota",
"model": "Corolla",
"creationDate": "2015-05-05",
"color": "WHITE",
"plateNumber": "Fmmf2421"
}
]
}
- Я вижу это в моем приложении весенней загрузки вставляет все данные для пользователя, генерирующего идентификатор для нового пользователя.
- Он также вставляет все данные для транспортных средств, генерирующих новые идентификаторы для транспортных средств, но в столбце FK в транспортных средствах он вставляет
null
всегда:
2020-07-12 15:55:20.169 TRACE 14700 --- [nio-8080-exec-2] o.h.type.descriptor.sql.BasicBinder : binding parameter [6] as [BIGINT] - [null]
Метод RestController для вставки пользователя:
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public User insert(@RequestBody User user) {
return userService.save(user);
}