Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

java - 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");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...