How to force Hibernate to return dates as java.util.Date instead of Timestamp?

dim1902 picture dim1902 · Mar 2, 2012 · Viewed 105.4k times · Source

Situation:

I have a persistable class with variable of java.util.Date type:

import java.util.Date;

@Entity
@Table(name = "prd_period")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Period extends ManagedEntity implements Interval {

   @Column(name = "startdate_", nullable = false)
   private Date startDate;

}

Corresponding table in DB:

CREATE TABLE 'prd_period' (
  'id_' bigint(20) NOT NULL AUTO_INCREMENT,
 ...
  'startdate_' datetime NOT NULL
)

Then I save my Period object to DB:

Period p = new Period();
Date d = new Date();
p.setStartDate();
myDao.save(p);

After then if I'm trying to extract my object from DB, it is returned with variable startDate of Timestamp type - and all the places where I'm trying to use equals(...) are returning false.

Question: are there any means to force Hibernate to return dates as object of java.util.Date type instead of Timestamp without explicit modification of every such variable (e.g it must be able just work, without explicit modification of existed variables of java.util.Date type)?

NOTE:

I found number of explicit solutions, where annotations are used or setter is modified - but I have many classes with Date-variables - so I need some centralized solution and all that described below is not good enough:

  1. Using annotation @Type: - java.sql.Date will be returned

    @Column
    @Type(type="date")
    private Date startDate;
    
  2. Using annotation @Temporal(TemporalType.DATE) - java.sql.Date will be returned

    @Temporal(TemporalType.DATE)
    @Column(name=”CREATION_DATE”)
    private Date startDate;
    
  3. By modifying setter (deep copy) - java.util.Date will be returned

    public void setStartDate(Date startDate) {
        if (startDate != null) {
            this.startDate = new Date(startDate.getTime());
        } else {
            this.startDate = null;
        }
    }
    
  4. By creation of my own type: - java.util.Date will be returned

Details are given here: http://blogs.sourceallies.com/2012/02/hibernate-date-vs-timestamp/

Answer

Nathan picture Nathan · Dec 2, 2012

A simple alternative to using a custom UserType is to construct a new java.util.Date in the setter for the date property in your persisted bean, eg:

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Column;

@Entity
public class Purchase {

    private Date date;

    @Column
    public Date getDate() {
        return this.date;
    }

    public void setDate(Date date) {
        // force java.sql.Timestamp to be set as a java.util.Date
        this.date = new Date(date.getTime());
    }

}