javaspring-boothibernatejpaspring-data-jpa

Spring-Data @Version-Property inspection does not work with primitives for Entity State Detection


From the official docs:

If a property annotated with @Version is present and null, or in case of a version property of primitive type 0 the entity is considered new. If the version property is present but has a different value, the entity is considered to not be new. From my understanding, spring will use even primitive verion field to check if entity is new or not.

However, in my testing, if I create an entity with a primitive version field, manually set Id, and try to save (JpaRepository.save()), spring still calls em.merge() (and not simply persist), which causes an additional select query.
Changing the type to Integer resolves the issue.

Sample entity:

//...other imports
import javax.persistence.Version;

@Entity
@Table(name = "test")
public class Test implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;

    @Id
    private Long id;

    @Version
    @NotNull
    @Column(name = "entity_version")
    private int entityVersion;
}

Moreoever, looking at the sources I find this block of code:

@Override
public boolean isNew(T entity) {

    if (versionAttribute.isEmpty() ||
versionAttribute.map(Attribute::getJavaType).map(Class::isPrimitive).orElse(false)) {
            return super.isNew(entity);
    }

    BeanWrapper wrapper = new DirectFieldAccessFallbackBeanWrapper(entity);

    return versionAttribute.map(it -> wrapper.getPropertyValue(it.getName()) == null).orElse(true);
    }

If I understand correctly, it check if the version field has primitive type, and if yes, simply calls super.isNew() method, which checks only Id.

Am I missing something?


Solution

  • Answer from spring-data github issues:

    The referenced fragment points to the commons part of the documentation with limited applicability. Is-New detection for all modules but JPA works that way, assuming that the initial value of a primitive version is zero and zero indicates a state before it has been inserted into the database. Once inserted in the database, the value is one.

    However, with JPA, we're building on top of Hibernate and we have to align with Hibernates mechanism that considers zero as first version number and so we cannot use primitive version columns to detect the is-new state.

    The Spring Data JPA Entity-State detection uses a slightly different wording at https://docs.spring.io/spring-data/jpa/reference/jpa/entity-persistence.html#jpa.entity-persistence.saving-entities.strategies, however, it doesn't point out that primitive version properties are not considered so I'm going to update the docs.