I'm using CrudRepository.save(Entity)
to insert an Entity with @ID
already populated.
I'm getting the following exception.
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.
I can understand the issue as @ID
field is already populated, AggregateChangeExecutor here is treating this action as DbAction.Update.
So, I wanted to know if there is any way I can use CrudRepository.save(Entity)
to insert a new entity with a predefined @ID
field as I've wanted to use @DomainEvent
hook on CrudRepository.save(Entity).
I kind of feel that this a bug in spring-data-jdbc
. Just wanted an opinion/solution here.
According to the Spring Data Refrence Documetnation , the underlying JPA EntiyManager uses three strategies to determine if an entity is new:
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 isnull
, then the entity is assumed to be new. Otherwise, it is assumed to be not new.Implementing
Persistable
: If an entity implementsPersistable
, Spring Data JPA delegates the new detection to theisNew(…)
method of the entity. See the JavaDoc for details.Implementing
EntityInformation
: You can customize theEntityInformation
abstraction used in theSimpleJpaRepository
implementation by creating a subclass ofJpaRepositoryFactory
and overriding thegetEntityInformation(…)
method accordingly. You then have to register the custom implementation ofJpaRepositoryFactory
as a Spring bean. Note that this should be rarely necessary. See the JavaDoc for details.
In your case, using the second strategy might be the most useful. Hope it helps.
It was pointed out to me, that the question was not about JPA, but spring-data-jdbc. This is correct but does not change the answer since the same behaviour is documented in Spring Data JDBC - Reference Documentation .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.