Issue
I have a Many-to-one relation with a Building object having multiple Room objects, but when i make the repository call for a building-object i get something like this:
{"id":3,"street":"Musterstreet","houseNumber":"10","postCode":"111111","city":"Heilbronn","rooms":[{},{}]}
where did i turn wrong that the Room-list doesnt show me any data of each Room-object, it clearly knows that there are 2 Room-objects in its list
my Entities look like this
@Entity
@Table(name = "buildings")
@NoArgsConstructor
@ToString(exclude = {"rooms"})
@Getter
@Setter
public class Building {
@Id
@GeneratedValue
private Integer id;
@NotNull
@Column(nullable = false)
private String street;
@NotNull
@Column(nullable = false)
private String houseNumber;
@NotNull
@Column(nullable = false)
private String postCode;
@NotNull
@Column(nullable = false)
private String city;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "building", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Room> rooms = new HashSet<>();
}
and
@Entity
@Table(name = "room")
@NoArgsConstructor
@ToString(exclude = {"building"})
public class Room{
@Id
@GeneratedValue
private Integer id;
@NotNull
@Column(nullable = false)
private String roomName;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "building_id", nullable = false)
private Building building;
}
straight forward repo interface
public interface BuildingRepository extends JpaRepository<Building, Integer> {
Optional<Building> findById(int id);
Optional<Building> findByStreet(String street);
}
at last the controller method with the call
@GetMapping("/buildings/{id}")
public ResponseEntity<Building> getBuildingById(@PathVariable("id") Integer id) {
Building building = buildingService.getBuildingById(id);
return new ResponseEntity<>(building, HttpStatus.OK);
}
what i want to do is to just work with the Building-object, so when i need a certain Room-object it can get extracted out of the list from the Building
Solution
Your Room
class is missing it's getters.
Add the following annotation:
@Getter
Spring uses Jackson by default, which generates the JSON by calling all public non-void methods which accept no arguments, or in other words, all accessors.
Answered By - adnan_e
Answer Checked By - Timothy Miller (JavaFixing Admin)