有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用crudepository。保存(实体)以使用springdatajdbc插入具有预定义@ID字段的实体

我正在使用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字段已经填充, AggregateChangeExecutorhere正在将此操作视为DbAction。更新

因此,我想知道是否有任何方法可以使用CrudRepository.save(Entity)插入一个带有预定义@ID字段的新实体,就像我想在crudepository上使用@DomainEvent钩子一样。保存(实体)

我觉得这是spring-data-jdbc中的一个bug。 我只是想要一个意见/解决方案


共 (1) 个答案

  1. # 1 楼答案

    根据Spring Data Refrence Documetnation,底层JPA EntityManager使用三种策略来确定实体是否是新的:

    1. Version-Property and Id-Property inspection (default): By default Spring Data JPA inspects first if there is a Version-property of non-primitive type. If there is the entity is considered new if the value is null. Without such a Version-property Spring Data JPA inspects the identifier property of the given entity. If the identifier property is null, then the entity is assumed to be new. Otherwise, it is assumed to be not new.

    2. Implementing Persistable: If an entity implements Persistable, Spring Data JPA delegates the new detection to the isNew(…) method of the entity. See the JavaDoc for details.

    3. Implementing EntityInformation: You can customize the EntityInformation abstraction used in the SimpleJpaRepository implementation by creating a subclass of JpaRepositoryFactory and overriding the getEntityInformation(…) method accordingly. You then have to register the custom implementation of JpaRepositoryFactory as a Spring bean. Note that this should be rarely necessary. See the JavaDoc for details.

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

    编辑

    有人向我指出,问题不在于JPA,而在于spring数据jdbc。这是正确的,但不会改变答案,因为相同的行为记录在Spring Data JDBC - Reference Documentation