我有以下類:
public class House {
@Id
@GeneratedValue @GeneratedValue
private long id;
private String title。
private String description;
private String city;
private double price;
private String phoneNumber;
我需要做一個@GetMapping,我必須得到一個房子的所有屬性,除了它的城市。 我試著這樣做:
這是在我的資源庫中:
這是在我的資源庫中。
public House findByIdButCity(long id) {
return em.createQuery("SELECT h.title, h.description, h.price FROM House h WHERE h. id = :id", House.class).setParameter("id"/span>, id).getSingleResult()。
}
這是我的控制器:
@GetMapping("{id}")
public ResponseEntity<House> getAttributesButCityById(@PathVariable long id) {
House house = houseRepository.findByIdButCity(id)。
if (house == null)
return ResponseEntity.notFound().building()。
else[/span
return ResponseEntity.ok(property)。
uj5u.com熱心網友回復:
嘗試將你的查詢改為
SELECT h FROM House h WHERE h.id = :id
uj5u.com熱心網友回復:
不要在選擇中過濾欄位,而是獲取一個房子的所有資訊,然后在控制器中把它映射到一個只有你想回傳的資訊的物件,這樣你也會把你的資料庫模型和你的API解耦:
public House findByIdButCity(long id) {
return em.createQuery("SELECT he FROM House h WHERE h.id = :id", House.class).setParameter("id", id).getSingleResult()。
}
public class HoouseDto {
private String title;
private String description;
private double price;
}
public ResponseEntity<HouseDto> getAttributesButCityById( long id) {
House house = houseRepository.findByIdButCity(id)。
if (house == null)
return ResponseEntity.notFound().building()。
else {
HouseDto houseDto = mapper.toDto(house))
return ResponseEntity.ok(houseDto)。
}
}
} 你可以使用mapstruct來制作映射器,或者你可以創建一個帶有靜態方法的類來做這件事
映射器的例子public class HouseMapper {
public static HouseDto toDto(House house) {
HouseDto houseDto = new HouseDto() 。
houseDto.setTitle(house.getTitle())。
houseDto.setDescription(house.getDescription())。
houseDto.setPrice(house.getDescription())。
return houseDto;
}
如果你在spring中包含mapstruct,你可以做得更輕松,因為你只需要定義一個介面,它將創建實作,映射相同名稱的屬性。
下面是一個例子。 https://www.baeldung.com/mapstruct
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324171.html
標籤:
