Space
Space

Reputation: 213

How to insert data with automatic value to createdDate and updatedDate using Spring, Hibernate?

I want to insert data with automatic insertion of created_at date time and respective updated_at date time.

I have a pojo as:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;

@Basic(optional = false)
@Column(name = "name")
private String name;

@Basic(optional = false)
@CreationTimestamp
@Column(name = "created_at")
@Temporal(TemporalType.TIMESTAMP)
private Date createdAt;

@UpdateTimestamp
@Column(name = "updated_at")
@Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;

And in my database, I have used DATETIME as a type for created_at and updated_at. But I am not being able to insert data rather it gives an error message not-null property references a null or transient value: com.project.test.entity.Stamp.createdAt.

I want to know the proper way to define my database schema for created_at and updated_at DateTime field to make it generate automatically.

Upvotes: 3

Views: 9065

Answers (2)

mdeterman
mdeterman

Reputation: 4389

Edited to include MySQL table information.

If you want your source of truth to be the database you can use @Generated and allow the database to set the create update timestamp.

@Generated(GenerationTime.INSERT)
@Basic(optional = false)
@Column(name = "created_at")
@Temporal(TemporalType.TIMESTAMP)
private Date createdAt;

@Generated(GenerationTime.ALWAYS)
@Column(name = "updated_at")
@Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;

This is for the MYSQL database you need set the update the DEFAULT and ON UPDATE for the column.

 createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
 updatedAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Upvotes: 3

Raju Sharma
Raju Sharma

Reputation: 2516

You can do something like below.

1) initialize your created and updated date using new Date() :

@Basic(optional = false)
@CreationTimestamp
@Column(name = "created_at")
@Temporal(TemporalType.TIMESTAMP)
private Date createdAt = new Date(); // initialize created date

@UpdateTimestamp
@Column(name = "updated_at")
@Temporal(TemporalType.TIMESTAMP)
private Date updatedAt = new Date(); // initialize updated date

2) and provide your setter method for updated date by new Date(), without passing any value to it :

@PreUpdate
public void setUpdatedAt() {  
    this.updatedAt= new Date(); 
}

Upvotes: 9

Related Questions