You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 a new entity with a primitive version field, manually set Id (business requirements to set it manually), and try to save (JpaRepository.save()), spring still calls em.merge() (and not simply em.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;
}
The text was updated successfully, but these errors were encountered:
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.
From the official docs:
However, in my testing, if I create a new entity with a primitive version field, manually set Id (business requirements to set it manually), and try to save (
JpaRepository.save()
), spring still callsem.merge()
(and not simplyem.persist()
), which causes an additional select query.Changing the type to Integer resolves the issue.
Sample entity:
The text was updated successfully, but these errors were encountered: