我创建了这段代码:
Sale sale = new Sale();
saleService.create(sale);
Vendor vendor = new Vendor("name");
Sale updatedSale = saleService.findById(sale.getId());
updatedSale.setVendor(vendor);
try {
saleService.update(updatedSale);
} catch (EntityNotFoundException ex) {
System.err.println("");
}
此外,销售与供应商级联:
@ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REFRESH}, targetEntity = Vendor.class)
@Cascade({
org.hibernate.annotations.CascadeType.SAVE_UPDATE,
org.hibernate.annotations.CascadeType.PERSIST
})
private Vendor vendor;
saleService 有以下代码:
@Transactional
public Sale create(Sale entity) {
Sale created = entity;
saleRepository.saveAndFlush(created);
return created;
}
@Transactional(rollbackFor = EntityNotFoundException.class)
public Calibration update(Calibration entity) throws EntityNotFoundException {
if (!calibrationRepository.exists(entity.getId())) {
throw new EntityNotFoundException();
}
return calibrationRepository.saveAndFlush(entity);
}
它也被注释为@Service
。存储库是一个实现 JpaRepository<Sale, Long>
的接口(interface).
我收到一条错误消息,指出 name
Vendor 的属性不能为 null,但为 null。
谢谢!
最佳答案
upd答案,对应问题的第一个版本已被完全删除 - 简而言之,它建议在实体更新后再次刷新更改。
当前的问题在于混合两种注释 - 第一个是属于 JPA 规范的 @ManyToOne
注释,第二个是 Hibernate 特定的 @Cascade
。
由于您在示例中没有执行任何 Hibernate 特定操作,因此解决方案是删除 @Cascade
注释并将 CascadeType.MERGE
添加到 @ManyToOne
注释。
关于java - 未使用 Hibernate 持久化实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30845714/