rudeTool
rudeTool

Reputation: 606

How do I automatically store Date in JPA entity?

I have a JPA entity in Spring where I have a created_at field of type Date. I want to automatically initialize it to current date. How can I achieve this? Here's my code:

public class ClientModel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private BigInteger id;
    private String client_id;
    private String client_name;
    private String client_secret;
    private String status;
    private Date created_at;
}

Currently I am doing this,

java.util.Date javaDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(javaDate.getTime());
client.setCreated_at(sqlDate);

Is there any alternative to this?

Upvotes: 1

Views: 4332

Answers (2)

Saurabh Singh
Saurabh Singh

Reputation: 218

I would advise in a more JPA-friendly way via events.

Example @PrePersist void onPrePersist() {created_at = new java.util.Date();}

This way entity will not be bind with Spring. So if the same entity needed in Non Spring environment then also it will work.

Upvotes: 0

pcsutar
pcsutar

Reputation: 1829

You can use CreatedDate annotation as shown in below example:

public class ClientModel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private BigInteger id;
    private String client_id;
    private String client_name;
    private String client_secret;
    private String status;

    @Column(name = "created_at", nullable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date created_at;
}

While creating new ClientModel, do not set any value for created_at. Spring will automatically initialize it to current date.

Upvotes: 1

Related Questions