javaspringhibernatespring-mvcspring-boot

How can you make a created_at column generate the creation date-time automatically like an ID automatically gets created?


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;

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?

My post method is as below:

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

Solution

  • JPA

    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.

    Hibernate

    Spring Data JPA