How can I use DB side default value while use Hibernate save?

社会主义新天地 提交于 2019-11-26 19:23:21

问题


I have a column in DB with default value as sysdate. I'm looking for a way to get that default value inserted while I'm not giving anything to corresponding property on app side. By the way, I'm using annotation-based configuration.

Any advice?


回答1:


The reason why the date column gets a null value when inserting, even though it is defined as default SYSDATE dbms-side, is that the default value for a column is only used if the column is not given a value in the query. That means it must not appear in the INSERT INTO sentence, even if it has been given null.

If you want to use the default SYSDATE on the DBMS side, you should configure the @Column with insertable=false in order to get the column out of your SQL INSERTs.

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "myDate", insertable=false)
private Date myDate;

Take into account that this approach will always ignore the value you provide to the property in your app when creating the entity. If you really want to be able to provide the date sometimes, maybe you should consider using a DB trigger to set the value instead of a default value.

There's an alternative to using the default SYSDATE definition of the DBMS. You could use the @PrePersist and @PreUpdate annotations to assign the current date to the property, prior to save/update, if and only if it has not been assigned yet:

@PrePersist
protected void onCreate() {
    if (myDate == null) { myDate = new Date(); }
}

This closely related question provides different approaches: Creation timestamp and last update timestamp with Hibernate and MySQL.




回答2:


If you are using Hibernate then you can just use @CreationTimestamp to insert default date.

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "create_date")
private Date createDate;

and @UpdateTimestamp to update the value if necessary

@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "modify_date")
private Date modifyDate;



回答3:


Just put insertable=false in you @Column definition

see this link for more information




回答4:


Or you can initialize the property of the POJO directly e.g:

//java code property declaration

private String surname = "default";


来源:https://stackoverflow.com/questions/14703697/how-can-i-use-db-side-default-value-while-use-hibernate-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!