我不确定我是否正确实施了一种负责从用户输入中插入产品的方法。主要类是:
Product.java
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String name;
private BigDecimal price;
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
@ManyToOne
@JoinColumn(name = "producer_id")
private Producer producer;
Producer.java
public class Producer {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "country_id")
private Country country;
@ManyToOne
@JoinColumn(name = "trade_id")
private Trade trade;
}
将产品添加到数据库的方法:
try {
var product = ProductUtil.createProductFromUserInput();
var category = OptionalHelper.of(categoryService
.getCategoryByName(product.getCategory().getName()))
.ifNotPresent(() ->
categoryService.addCategoryToDb(product.getCategory()).orElseThrow(() -> new AppException("Category is null")));
var country = OptionalHelper.of(countryService
.getCountryByName(product.getProducer().getCountry().getName()))
.ifNotPresent(() ->
countryService.addCountryToDb(product.getProducer().getCountry()).orElseThrow(() -> new AppException("Country is null")));
product.getProducer().setCountry(country);
var trade = OptionalHelper.of(tradeService
.getTradeByName(product.getProducer().getTrade().getName()))
.ifNotPresent(() ->
tradeService.addTradeToDb(product.getProducer().getTrade()).orElseThrow(() -> new AppException("Trade is null")));
product.getProducer().setTrade(trade);
var producer = OptionalHelper.of(producerService
.getProducerByNameAndTradeAndCountry(
product.getProducer().getName(), product.getProducer().getTrade(), product.getProducer().getCountry()))
.ifNotPresent(() ->
producerService.addProducerToDb(product.getProducer()).orElseThrow(() -> new AppException("Producer is null")));
product.setCategory(category);
product.setProducer(producer);
productService.addProductToDbFromUserInput(product);
} catch (Exception e) {
log.info(e.getMessage());
log.error(Arrays.toString(e.getStackTrace()));
throw new AppException(String.format("%s;%s: %s", PRODUCT, ERROR_WHILE_INSERTING, e.getMessage()));
}
问题是我在坚持生产者,产品和交易的同时不能进行级联,因为存在关于按名称,国家和行业进行生产唯一性的要求,交易必须按名称唯一,产品必须按名称唯一,类别以及国家/地区,国家/地区在名称上必须唯一。\等。
换句话说,如果我要进行级联插入操作,可能会出现重复的键错误,因此我必须像上述方法一样“手动”检查数据库中是否已经有国家,行业和产品。问题是,我是否可以通过另一种方式来实现,而更多地采用“自动方式”?