Setting a JPA timestamp column to be generated by the database?
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.
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
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.
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.
Solution 1:
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;
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.
Solution 2:
I realize this is a bit late, but I've had success with annotating a timestamp column with
@Column(name="timestamp", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
This should also work with CURRENT_DATE
and CURRENT_TIME
. I'm using JPA/Hibernate with Oracle, so YMMV.
Solution 3:
@Column(nullable = false, updatable = false)
@CreationTimestamp
private Date created_at;
this worked for me. more info