Map MySql datetime to hibernate

11,289

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.

Share:
11,289
Eddy
Author by

Eddy

Updated on June 04, 2022

Comments

  • Eddy
    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 is

    private java.sql.Timestamp startTime;
    

    I tried setting various types for the listingTime property in my hibernate.cfg.xml but it doesn't change the all zeroes. What am I missing?

    • Jordi Castilla
      Jordi Castilla over 8 years
      how do you get Timestamp ?
    • Eddy
      Eddy over 8 years
      How do you mean? It's mapped like I wrote in the question.
    • beemaster
      beemaster over 7 years
      @Eddy: Why did you chose java.sql.Timestamp type of field instead of java.util.Date?
    • Eddy
      Eddy over 7 years
      @beemaster it seems to be better for integration with Hibernate / Spring
  • Eddy
    Eddy over 8 years
    I tried type="timestamp" in my Product.hbm.xml but it seems to have no effect.
  • Eddy
    Eddy over 8 years
    I'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
    Ferdinand Neman over 8 years
    There you go, I edited my answer, adding hbm.xml sample