I have two model classes:
Car which has owner field:
import lombok.Data;
import javax.persistence.*;
@Entity
@Data
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String carBrand;
private String modelOfCar;
private String gearbox;
private int yearProduction;
private int mileage;
private String status;
@ManyToOne
@JoinColumn(name = "owner_id")
private Owner owner;
}
And Owner which has cars field
@Entity
@Data
public class Owner implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String nameOfOwner;
private String surnameOfOwner;
@OneToMany(mappedBy = "owner")
private List<Car> cars = new ArrayList<>()
public void addCarToOwner(Car car) {
cars.add(car);
}
}
I tried to add some sample data to embedded h2 DB within this data:
Car car1 = new Car();
car1.setCarBrand("asd");
car1.setModelOfCar("asd");
car1.setGearbox("asd");
car1.setYearProduction(22018);
car1.setMileage(321000);
car1.setStatus("Available");
Car car2 = new Car();
car2.setCarBrand("asd");
car2.setModelOfCar("asd");
car2.setGearbox("asd");
car2.setYearProduction(2011);
car2.setMileage(6801020);
car2.setStatus("Available");
Owner owner1 = new Owner();
owner1.setNameOfOwner("asd");
owner1.setSurnameOfOwner("asd");
owner1.addCarToOwner(car1);
Owner owner2 = new Owner();
owner2.setNameOfOwner("asd");
owner2.setSurnameOfOwner("asd");
owner2.addCarToOwner(car2);
carRepository.save(car1);
carRepository.save(car2);
ownersRepository.save(owner1);
ownersRepository.save(owner2);
When I check state of owner repository with findAll()
method I get owner and empty list of his cars. When I run findAll()
for cars repository I have null for owner, because I did not set it, but how can I set it when owner needs cars, and car need owner?
All this causes that when I try to fetch user with given ID I get an empty list of cars for him.