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

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

问题描述

我在数据库中有一个列,默认值为 sysdate.我正在寻找一种方法来插入该默认值,而我没有为应用程序端的相应属性提供任何内容.顺便说一下,我正在使用基于注释的配置.

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.

有什么建议吗?

推荐答案

日期列在插入时得到null值的原因,即使它被定义为default SYSDATE dbms-side,是列的 default 值仅在查询中未为该列指定值时才使用.这意味着它不能出现在 INSERT INTO 语句中,即使它被赋予了 null.

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.

如果您想在 DBMS 端使用 default SYSDATE,您应该使用 insertable=false 以便从 SQL 中获取该列INSERTs.

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.

除了使用 DBMS 的 default SYSDATE 定义之外,还有一种替代方法.您可以使用 @PrePersist@PreUpdate 在保存/更新之前,将当前日期分配给属性的注释,当且仅当尚未分配时:

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(); }
}

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

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

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

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