如何使用Spring,Hibernate将具有自动值的数据插入到createdDate和updatedDate中? [英] How to insert data with automatic value to createdDate and updatedDate using Spring, Hibernate?
问题描述
我有一个pojo:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(可选= false)
@Column(name =id)
私人整数ID;
@Basic(可选= false)
@Column(name =name)
私有字符串名称;
@Basic(可选= false)
@CreationTimestamp
@Column(name =created_at)
@Temporal(TemporalType.TIMESTAMP)
private日期createdAt;
@UpdateTimestamp
@Column(name =updated_at)
@Temporal(TemporalType.TIMESTAMP)
private更新日期;
在我的数据库中,我使用DATETIME作为created_at和updated_at的类型。但是我无法插入数据,因为它提供了一条错误消息非空属性引用空值或瞬时值:com.project.test.entity.Stamp.createdAt。
我想知道为created_at和updated_at DateTime字段定义我的数据库模式以使其自动生成的正确方法。
您可以执行下面的操作。
1)使用 new Date():
@Basic(可选= false)
@CreationTimestamp
@Column(name =created_at )
@Temporal(TemporalType.TIMESTAMP)
私人日期createdAt = new Date(); //初始化创建日期
@UpdateTimestamp
@Column(name =updated_at)
@Temporal(TemporalType.TIMESTAMP)
私有日期updatedAt = new Date(); //初始化更新日期
2)并通过新日期提供更新日期的setter方法(),而不传递任何值:
@PreUpdate
public void setUpdatedAt(){
this.updatedAt = new Date();
}
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.
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();
}
这篇关于如何使用Spring,Hibernate将具有自动值的数据插入到createdDate和updatedDate中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!