Map MySql datetime to hibernate
Solution 1
Better use annotations like this:
...
@Column
@Type(type="timestamp")
private Date listing_time;
OR you can do it this way, and if you don't want it to change see the "updateable"
@Column(name = "created", nullable = false, updatable=false)
@Temporal(TemporalType.TIMESTAMP)
private Date created;
Solution 2
With JPA, Use temporal.
<entity class="com.package.of.my.entities.MyEntity" name="MyEntity">
<attributes>
<basic name="startTime">
<temporal>TIMESTAMP</temporal>
</basic>
</attributes>
</entity>
With Hibernate (hbm.xml), User
<hibernate-mapping package="com.package.of.my.entities">
<class name="MyEntity">
<timestamp name="startTime" column="START_TIME" />
</class>
</hibernate-mapping>
Or in annotation
@Basic
@Temporal(TemporalType.TIMESTAMP)
private java.sql.Timestamp startTime;
Alternatively is to use Long datatype to store your timestamp. So, using annotation, you declare in your entity :
@Basic
private Long startTime;
public void setStartTime(Long startTime) {
this.startTime = startTime;
}
public Long getStartTime() {
return startTime;
}
and in your logic, you do
Date dateStartTime = new Date();
entity.setStartTime(dateStartTime.getTime());
To set the date property...and
Date dateStartTime = new Date(entity.getStartTime());
To get the date property.
Eddy
Updated on June 04, 2022Comments
-
Eddy almost 2 years
I have a
datetime
field in my MySql database. A typical entry looks like this:2015-08-26 11:45:48
.But by the time it reaches my app the hours, minutes and seconds are always
00:00:00
.This is the mapping entry:
<property name="listingTime" column="listing_time"/>
The field in my
Java
class isprivate java.sql.Timestamp startTime;
I tried setting various types for the
listingTime
property in myhibernate.cfg.xml
but it doesn't change the all zeroes. What am I missing?-
Jordi Castilla over 8 yearshow do you get
Timestamp
? -
Eddy over 8 yearsHow do you mean? It's mapped like I wrote in the question.
-
beemaster over 7 years@Eddy: Why did you chose
java.sql.Timestamp
type of field instead ofjava.util.Date
? -
Eddy over 7 years@beemaster it seems to be better for integration with Hibernate / Spring
-
-
Eddy over 8 yearsI tried type="timestamp" in my Product.hbm.xml but it seems to have no effect.
-
Eddy over 8 yearsI'm using hbm.xml. This is my property: <property name="startTime" type="timestamp" column="listing_time"/>. How do you specify temporal in it?
-
Ferdinand Neman over 8 yearsThere you go, I edited my answer, adding hbm.xml sample