java - 未使用 Hibernate 持久化实体

标签 java spring hibernate jpa

我创建了这段代码:

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/

相关文章:

mysql - 为什么在数据库中直接更改时 Hibernate 响应没有反射(reflect)出来?

java - 为什么我不能在链表上使用 DescendingIterator?

java - 显示 servlet 嵌入的 pdf 文件

java - 关闭子窗口时关闭父窗口

java - 将数据保存到文件的最佳方法是什么?

spring - 本地主机与公共(public) IP 地址上的不同身份验证

java - 我可以使用 HashMap 在 Spring Boot 中选择要 Autowiring 的接口(interface) (DAO) 吗?

带 html 复选框的 spring 表单 Controller

java - 使用 UUID 作为主键时,Hibernate 得到错误的 ID 值

java - 通过 Spring 将字段注入(inject) Hibernate 加载的实体中