Space Space - 3 years ago 158
Java Question

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.

Answer Source

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(); 
 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download