[英]Spring Boot API Rest with DTO and @manytoone relationship - best practice
我有以下配置:
產品價格實體
@Entity
@Table(name = "PRODUCTPRICE")
public class ProductPriceEntity {
...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SUPERMARKET_STORE_ID", nullable = false)
private SupermarketStoreEntity store;
...
}
產品價格新請求
@Setter @Getter
public class ProductPriceNewRequest {
...
private Long storeId;
...
}
產品價格控制器Impl
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<ProductPriceResponse> save(@PathVariable(value = "product_id", required = true) Long productId, @RequestBody @Valid ProductPriceNewRequest productPriceNewRequest) {
ProductEntity productEntity = productService.findById(productId);
ProductPriceEntity productPriceEntity = modelMapper.map(productPriceNewRequest, ProductPriceEntity.class);
productPriceEntity.setProduct(productEntity);
productPriceEntity = service.insert(productPriceEntity);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(productPriceEntity.getId())
.toUri();
ProductPriceResponse productPriceResponse = modelMapper.map(productPriceEntity, ProductPriceResponse.class);
return ResponseEntity.created(location).body(productPriceResponse);
}
產品價格反應
@Getter @Setter
public class ProductPriceResponse {
...
private String supermarket;
private String store;
...
}
它有效,但我無法返回 DTO。 Supermarket 和 store 在 ProductPriceResponse 上為 null。
嗯,那我改了級聯store屬性關系。
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "SUPERMARKET_STORE_ID", nullable = false)
private SupermarketStoreEntity store;
我收到了這個錯誤:
“傳遞給持久化的分離實體:model.SupermarketStoreEntity;嵌套異常是 org.hibernate.PersistentObjectException:傳遞給持久化的分離實體:model.SupermarketStoreEntity”
那講得通。 Modelmapper 將一個長 storeId 轉換為一個 SupermarketStoreEntity,只有 id 和分離的 ...
最后我的問題是:什么是最佳實踐?
我應該獲取 storeId 並且不轉換為分離的 SupermarketStoreEntity 並在 ProductPriceControllerImpl 上找到您的 storeId 的 SupermarketStoreEntity 嗎?
或不。 我應該刪除級聯並在保存 ProductPriceEntity 之后我應該獲取 ProductPriceEntity 保存嗎? 我懷疑商店和超市仍然會變空,因為級聯不在那里。
謝謝你們
猜猜最佳實踐是引入一個@Service 類,在那里你有一個帶有@Transactional 注釋的方法。 服務被注入控制器,所有實體的加載和保存都發生在那里。 這應該有助於解決分離錯誤。
我不是級聯屬性的忠實粉絲,並且更喜歡在代碼中做這些事情 - 但這更多是一種意見。
也許您想看看https://bootify.io - 您可以在那里使用 REST api 定義您的數據庫,並了解控制器和服務的最佳實踐。:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.