繁体   English   中英

使用 CrudRepository.save(Entity) 使用 spring-data-jdbc 插入具有预定义 @ID 字段的实体

[英]Using CrudRepository.save(Entity) to insert an Entity with predefined @ID field using spring-data-jdbc

我正在使用CrudRepository.save(Entity)插入一个已填充@ID的实体。

我收到以下异常。

Caused by: org.springframework.dao.IncorrectUpdateSemanticsDataAccessException: Failed to update entity [com.comanyname.repository.Entiy.class]. Id [ed384316-9c22-4b63-90fd-ec02fdac2b86] not found in database.

我可以理解这个问题,因为@ID字段已经填充, 这里的 AggregateChangeExecutor 将此操作视为 DbAction.Update。

所以,我想知道是否有任何方法可以使用CrudRepository.save(Entity)插入具有预定义@ID字段的新实体,因为我想在 CrudRepository.save(Entity) 上使用@DomainEvent挂钩。

我觉得这是spring-data-jdbc中的一个错误。 只是想在这里发表意见/解决方案。

根据 Spring 数据参考文档,底层 JPA EntiyManager 使用三种策略来确定实体是否是新的:

  1. 版本属性和 Id 属性检查(默认):默认情况下 Spring 数据 JPA 首先检查是否存在非原始类型的版本属性。 如果值为null ,则该实体被视为新实体。 如果没有这样的版本属性 Spring 数据 JPA 检查给定实体的标识符属性。 如果标识符属性是null ,则假定实体是新的。 否则,假定它不是新的。

  2. 实现Persistable :如果实体实现Persistable ,则 Spring 数据 JPA 将新检测委托给实体的 isNew isNew(…)方法。 有关详细信息,请参阅JavaDoc

  3. 实现EntityInformation :您可以通过创建JpaRepositoryFactory的子类并相应地覆盖getEntityInformation(…)方法来自定义SimpleJpaRepository实现中使用的EntityInformation抽象。 然后,您必须将 JpaRepositoryFactory 的自定义实现注册为JpaRepositoryFactory bean。 请注意,这应该很少需要。 有关详细信息,请参阅JavaDoc

在您的情况下,使用第二种策略可能是最有用的。 希望能帮助到你。

编辑

有人向我指出,问题不是关于 JPA,而是关于 spring-data-jdbc。 这是正确的,但不会改变答案,因为Spring 数据 JDBC - 参考文档中记录了相同的行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM