'How to get information from the both sides of @ManytoMany relationship?
I'm new to JPA and I'm trying to build a @ManyToMany relationship between two entities: car.java and part.java. I wrote a method, which saves the relationship in a third table: car_part.
car entity:
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "car_part", joinColumns = @JoinColumn(name = "car_id"),
inverseJoinColumns = @JoinColumn(name = "part_id"))
private Set<Part> parts = new HashSet<>();
part entity:
@JsonIgnore
@ManyToMany(mappedBy = "parts")
private Set<Car> cars = new HashSet<>();
car controller:
@PutMapping("/cars/{carId}/parts/{partId}")
public Car addPartToCar(@PathVariable Long carId, @PathVariable Long partId) {
Car car = carManager.findById(carId).get();
Part part = partManager.findById(partId).get();
car.addPart(part);
return carManager.save(car);
}
When I run a "getCar" method, a part is included:
{
"id": 3,
"brand": "vw",
"numberPlate": "12345",
"parts": [
{
"id": 2,
"partName": "part1",
"price": "200"
}
]
But when I run a "getPart" method, a car is not included:
{
"id": 2,
"partName": "part1",
"price": "200"
}
My Question: Why is a car not included, when I'm searching for a part? I searched and I found out, I should add the relationship to the both sides. So I should probably add a car to the part like this, but I'm getting a LazyInitializationException
@PutMapping("/cars/{carId}/parts/{partId}")
public Car addPartToCar(@PathVariable Long carId, @PathVariable Long partId) {
Car car = carManager.findById(carId).get();
Part part = partManager.findById(partId).get();
car.addPart(part);
part.getCars().add(car);
partManager.save(part);
return carManager.save(car);
}
Any help you can give would be greatly appreciated.
UPDATE: I removed @JsonIgnore but now I get the HttpMessageNotWritableException
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
