Reputation: 13
I have Enity with field
@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updateDate")
private Date updateDate;
While I'm doing an update using Hibernate this field changes the date to the current one automatically
session.save(user); //IT'S OK
bat I want only set Email by Spring Data
@Transactional
@Modifying
@Query("update User e set e.email = :email where e.id = :id")
public void setEmail(@Param("id") Long id, @Param("email") String email);
And while the email change doesn't the field for the current time. Why?
Upvotes: 1
Views: 3851
Reputation: 30474
Try to use this (not tested):
@Transactional
@Modifying
@Query("
update User e
set e.email = :email,
e.updateDate = ?#{T(java.sql.Timestamp).valueOf(
T(java.time.LocalDateTime).now()
)}
where e.id = :id
")
public void setEmail(@Param("id") Long id, @Param("email") String email);
SpEL support in Spring Data JPA @Query definitions
Or even this variant:
@Transactional
@Modifying
@Query("
update User e set
e.email = :email,
e.updateDate = :curTime
where e.id = :id
")
void setEmail(
@Param("id") Long id,
@Param("email") String email,
@Param("curTime") Timestamp curTime)
)
default void setEmail(Long id, String email) {
setEmail(id, email, Timestamp.valueOf(LocalDateTime.now()));
}
Upvotes: 2
Reputation: 2143
You're using a bulk update statement, which means the User entity isn't managed by the entity manager while performing that update, and so the timestamp won't be automatically updated.
The following would cause the timestamp to be updated...
User user = userRepository.findOne(userId);
user.setEmail(email);
userRepository.save(user);
Upvotes: 0
Reputation: 5274
According to UpdateTimestamp
documentation
Marks a property as the update timestamp of the containing entity. The property value will be set to the current VM date whenever the owning entity is updated.
I guess you will have to remove it and do it manually on the required occassions
Upvotes: 0