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

Brett Freeman :

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");
}
dimitrisli :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=431792&siteId=1
Recommended