首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >@CreationTimestamp @UpdateTimestamp在更新实体类后不可用

@CreationTimestamp @UpdateTimestamp在更新实体类后不可用
EN

Stack Overflow用户
提问于 2019-09-21 14:55:02
回答 1查看 341关注 0票数 0

我有一个要更新的User实体。数据被更新了,甚至更新的响应也是由spring-data-jpasave方法返回的,但是createdupdated是null。我在数据库中检查了一下,updated列的值被更新为1。而且,更新之后,我使用spring-data-jpafind方法之一获得了数据,并且我得到了正确的结果。这次createdupdated不是null。

代码语言:javascript
运行
复制
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实现。

代码语言:javascript
运行
复制
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;
}
EN

回答 1

Stack Overflow用户

发布于 2019-09-21 17:08:18

您可以使用Spring中的@CreatedDate@LastModifiedDate批注。

代码语言:javascript
运行
复制
@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配置

代码语言:javascript
运行
复制
@Configuration
@EnableJpaAuditing
public class ApplicationConfiguration {
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58037985

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档