我与一个具有多个Room对象的Building对象有一个多对一关系,但是当我调用一个building-object的存储库时,我得到了如下所示的结果:{"id":3,"street":"Musterstreet","houseNumber":"10","postCode":"111111","city":"Heilbronn","rooms":[{},{}]}
我哪里搞错了,Room-list没有显示每个Room-object的任何数据,它清楚地知道列表中有2个Room-object
我的实体如下所示
@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<>();
}
和
@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;
}
直接回购接口
public interface BuildingRepository extends JpaRepository<Building, Integer> {
Optional<Building> findById(int id);
Optional<Building> findByStreet(String street);
}
最后调用控制器方法
@GetMapping("/buildings/{id}")
public ResponseEntity<Building> getBuildingById(@PathVariable("id") Integer id) {
Building building = buildingService.getBuildingById(id);
return new ResponseEntity<>(building, HttpStatus.OK);
}
我想做的是只使用Building-object,这样当我需要某个Room-object时,它就可以从Building的列表中提取出来
3条答案
按热度按时间klh5stk11#
您的
Room
类缺少它的getter。添加以下注解:
Spring默认使用Jackson,它通过调用所有不接受参数的公共非void方法(换句话说,所有访问器)来生成JSON。
t98cgbkg2#
正如我所看到的,您的
Room
类中没有任何 * getter * 和 * setter *,这与您的Building
类不同,您在其中设置了Lombok注解。因此,Jackson(spring-boot默认使用的)可能无法在将对象从控制器序列化为JSON时获取字段值,尽管“rooms”集合有一些实体。另外我还得提一下其他问题:
4c8rllxm3#
在您的Room类中,您没有提到getter。