【发布时间】:2020-11-09 23:32:08
【问题描述】:
我有以下配置:
ProductPriceEntity
@Entity
@Table(name = "PRODUCTPRICE")
public class ProductPriceEntity {
...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SUPERMARKET_STORE_ID", nullable = false)
private SupermarketStoreEntity store;
...
}
ProductPriceNewRequest
@Setter @Getter
public class ProductPriceNewRequest {
...
private Long storeId;
...
}
ProductPriceControllerImpl
@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);
}
ProductPriceResponse
@Getter @Setter
public class ProductPriceResponse {
...
private String supermarket;
private String store;
...
}
它有效,但我无法返回 DTO。 Supermarket 和 store 在 ProductPriceResponse 上为空。
嗯,那我改了级联的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 将 long storeId 转换为只有 id 和分离的 SupermarketStoreEntity ...
最后我的问题是:最佳做法是什么?
我是否应该获取 storeId 并且不转换为分离的 SupermarketStoreEntity 并在 ProductPriceControllerImpl 上使用您的 storeId 找到 SupermarketStoreEntity?
或者没有。我应该删除级联并在保存 ProductPriceEntity 后我应该获取保存的 ProductPriceEntity 吗?我怀疑商店和超市仍然会因为级联不存在而变为空。
谢谢大家
【问题讨论】:
标签: java spring spring-boot spring-data dto