Issue
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?
Solution
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.
Answered By - pcsutar