如何在使用Hibernate保存时使用DB端默认值? [英] How can I use DB side default value while use Hibernate save?

查看:126
本文介绍了如何在使用Hibernate保存时使用DB端默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在DB中有一个列,默认值为 sysdate 。我正在寻找一种方法来获得插入的默认值,而我没有给任何应用程序端的相应属性。
顺便说一句,我使用基于注释的配置。



任何建议?

解决方案

即使它被定义为 default SYSDATE dbms-side,插入时的 null 值是<$ c仅当列未在查询中被赋予一个值时,才使用列的$ c> default 值。这意味着它不能出现在 INSERT INTO 句子中,即使它已被赋予 null



如果你想在DBMS端使用默认SYSDATE ,你应该配置 @Column insertable = false ,以便从SQL中删除列 INSERT s。

  @Temporal(TemporalType.TIMESTAMP)
@Column(name =myDate,insertable = false)
private日期myDate;请注意,此方法将始终忽略您在创建应用程序时为属性提供的值该实体。如果你真的希望能够提供日期,也许你应该考虑使用DB触发器来设置值而不是默认值。



使用DBMS的默认SYSDATE 定义。您可以使用 @PrePersist @PreUpdate 注释在保存/更新之前将当前日期分配给属性,当且仅当尚未分配时:

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

这个密切相关的问题提供了不同的方法:使用Hibernate和MySQL创建时间戳和上次更新时间戳


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?

解决方案

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.

这篇关于如何在使用Hibernate保存时使用DB端默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆