我有一个要更新的User
实体。数据被更新了,甚至更新的响应也是由spring-data-jpa
的save
方法返回的,但是created
和updated
是null。我在数据库中检查了一下,updated
列的值被更新为1。而且,更新之后,我使用spring-data-jpa
的find
方法之一获得了数据,并且我得到了正确的结果。这次created
和updated
不是null。
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
@Column(name = "created", updatable = false, nullable = false)
@CreationTimestamp
@JsonSerialize(using = LocalDateTimeSerializer.class) @JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime created;
@Column(name = "updated")
@UpdateTimestamp
@JsonSerialize(using = LocalDateTimeSerializer.class) @JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime updated;
我不能责怪save
方法,因为它会返回另一个字段的更新值。可能在@UpdateTimestamp
和@CreationTimestamp
的工作中有一些可疑的地方,或者它与spring-data-jpa
的兼容性我不确定。
使用spring-data-jpa
的一个快速观察:如果我使用saveAndFlush
而不是save
,我会得到updated
作为有效值,但created
仍然是空的。以下是debug的截图:
我使用Hibernate
作为JPA
实现。
public interface CompanyDao extends CrudRepository<Company, Integer> { }
public User update(Integer userId, User user) {
User existingUser = userDao.findById(userId).orElseThrow(() -> new ResourceNotFoundException("User not found"));
user.setCompany(existingUser.getCompany());
User updatedUser = userDao.save(user);
return updatedUser;
}
发布于 2019-09-21 17:08:18
您可以使用Spring中的@CreatedDate
和@LastModifiedDate
批注。
@Entity
@EntityListeners(AuditingEntityListener.class)
public class User {
@Column(name = "created_at")
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date createdAt;
@Column(name = "updated_at", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
private Date updatedAt;
}
要做到这一点,您需要使用注释@EnableJpaAuditing
来注释spring配置
@Configuration
@EnableJpaAuditing
public class ApplicationConfiguration {
}
https://stackoverflow.com/questions/58037985
复制相似问题