如何使created_at列像自动创建ID一样自动生成创建日期时间? [英] How can you make a created_at column generate the creation date-time automatically like an ID automatically gets created?

查看:400
本文介绍了如何使created_at列像自动创建ID一样自动生成创建日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个实体,如下所示:

I currently have an Entity as below:

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long productId;
    private String productImage;
    private String productTitle;
    private String productDescription;
    private Integer productPrice;
    private Date createdAt;
    private Date updatedAt;

在创建此对象时,createdAt和updatedAt的值在数据库中显示为空,并且想知道如何实现代码,以便自动插入createdAt和updateAt?

Upon creation of this object, the value of createdAt and updatedAt shows null in the database and was wondering how I can implement code so that createdAt and updateAt automatically gets inserted?

我的发布方法如下:

@PostMapping("/products")
public ProductResponse createProduct(@Validated @RequestBody ProductForm productForm) {
    Product product = productForm.asProduct();
    Product createdProduct = productRepository.save(product);
    return new ProductResponse(createdProduct, "Product created");
}

推荐答案

JPA

没有什么比直接注释Timestamp字段更方便的了,但是您可以使用@PrePersist@PreUpdate注释,并且可以毫不费力地获得相同的结果.

There isn't anything as convenient as annotating the Timestamp field directly but you could use the @PrePersist, @PreUpdate annotations and with little effort achieve the same results.

休眠

  • @CreationTimestamp - Documentation
  • @UpdateTimestamp - Documentation

Spring Data JPA

  • @CreatedDate - Documentation
  • @LastModifiedDate - Documentation

这篇关于如何使created_at列像自动创建ID一样自动生成创建日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆