设置由数据库生成的 JPA 时间戳列?

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

问题描述

在我的 SQL Server 2000 数据库中,我有一个名为 lastTouched 的类型为 DATETIME 的时间戳(在函数中,不在数据类型中)列设置为 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.

推荐答案

我通过将代码更改为解决了这个问题

I fixed the issue by changing the code to

@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 时间戳列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:在 Java 中格式化时间戳 下一篇:如何从 java.sql.Timestamp 转换为 java.util.Date?

相关文章