Update @Updatetimestamp without changeing data of entity

Viewed 155

A ChildEntity has a many-to-one relation to a ParentEntity

The ParentEntity, has a:

@Version
@UpdateTimestamp
protected LocalDateTime modificationTime;

The requirement is that modificationTime of ParentEntity Row must be updated, when a ChildEntity is created or modified (in a @Transactional context) by ChildRepository extends JPARepository

The only way we currently see, is to create a method updateModificationTime and set it explicitly, wondering if there is a better way?

How can we update the @UpdateTimestamp annotated modificationTime without changeing any data of the ParentEntity?

github repo: https://github.com/daveyx/spring-playground/tree/main/210427-datatest

testcase: https://github.com/daveyx/spring-playground/blob/main/210427-datatest/src/test/java/com/example/datatest/child/ChildServiceIntegrationTest.java

1 Answers

As suggested by Chris, OPTIMISTIC_FORCE_INCREMENT seems to be a "correct" way for us. Getting the parent entity within the transactional context, updates the @UpdateTimestamp annotated property:

public interface ParentRepository extends JpaRepository<ParentEntity, Long> {

@Lock(LockModeType.OPTIMISTIC_FORCE_INCREMENT)
@Query("SELECT pe FROM ParentEntity pe WHERE pe.id = :parentId")
ParentEntity findByIdForceIncrement(@Param("parentId") Long parentEntityId);
Related