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

Setting a JPA timestamp column to be generated by the database?(设置由数据库生成的 JPA 时间戳列?)
本文介绍了设置由数据库生成的 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 时间戳列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)