设置要由数据库生成的 JPA 时间戳列? [英] Setting a JPA timestamp column to be generated by the database?

查看:32
本文介绍了设置要由数据库生成的 JPA 时间戳列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 SQL Server 2000 数据库中,我有一个名为 lastTouchedDATETIME 类型的时间戳(在函数中而不是数据类型中)列设置为 getdate() 作为其默认值/绑定.

In my SQL Server 2000 database, I have a timestamp (in function not in data type) column of type DATETIME named lastTouched set to getdate() as its default value/binding.

我正在使用 Netbeans 6.5 生成的 JPA 实体类,并在我的代码中有这个

I am using the Netbeans 6.5 generated JPA entity classes, and have this in my code

@Basic(optional = false)
@Column(name = "LastTouched")
@Temporal(TemporalType.TIMESTAMP)
private Date lastTouched;

然而,当我尝试将对象放入数据库时​​,我得到了,

However when I try to put the object into the database I get,

javax.persistence.PersistenceException: org.hibernate.PropertyValueException: not-null property references a null or transient value: com.generic.Stuff.lastTouched

我已尝试将 @Basic 设置为 (optional = true),但这会引发异常,指出数据库不允许 nullTIMESTAMP 列的 code> 值,它不是设计的.

I've tried setting the @Basic to (optional = true), but that throws an exception saying the database doesn't allow null values for the TIMESTAMP column, which it doesn't by design.

ERROR JDBCExceptionReporter - Cannot insert the value NULL into column 'LastTouched', table 'DatabaseName.dbo.Stuff'; column does not allow nulls. INSERT fails.

我以前让它在纯 Hibernate 中工作,但后来我切换到 JPA 并且不知道如何告诉它应该在数据库端生成此列.请注意,我仍然使用 Hibernate 作为我的 JPA 持久层.

I previously got this to work in pure Hibernate, but I have since switched over to JPA and have no idea how to tell it that this column is supposed to be generated on the database side. Note that I am still using Hibernate as my JPA persistence layer.

推荐答案

我通过将代码更改为

@Basic(optional = false)
@Column(name = "LastTouched", insertable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date lastTouched;

因此在生成 SQL 插入时忽略时间戳列.不确定这是否是解决此问题的最佳方法.欢迎反馈.

So the timestamp column is ignored when generating SQL inserts. Not sure if this is the best way to go about this. Feedback is welcome.

这篇关于设置要由数据库生成的 JPA 时间戳列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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