Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I map a Java date to DATETIME in mysql (by default its TIMESTAMP) with Hibernate annotations

All my db tables should have an endTime field which by default should be END_OF_TIME or something like that. I am not happy about the 2038 limitation so I want endTime to be of type DATETIME in mysql.

My Java code is:

@MappedSuperclass @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) public class BaseDBEntity { @Id @Column(length=36) public String id;  @Temporal(TemporalType.TIMESTAMP)  public Date startTime;  @Temporal(TemporalType.TIMESTAMP)  public Date endTime;  public BaseDBEntity() { }  } 

I can work around by creating the table manually with an endTime field of type DATETIME, and than map the entity endTime to that column, however I would like Hibernate to generate the tables automatically - how can I do that?

like image 903
user1023622 Avatar asked Nov 01 '11 12:11

user1023622


People also ask

What is @basic annotation in hibernate?

We can use the @Basic annotation to mark a basic type property: @Entity public class Course { @Basic @Id private int id; @Basic private String name; ... } In other words, the @Basic annotation on a field or a property signifies that it's a basic type and Hibernate should use the standard mapping for its persistence.

What is @temporal TemporalType timestamp?

It helps to convert the date and time values from Java object to compatible database type and will retrieve it back to the application. supports; @Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.DATE) @Temporal(TemporalType.TIME)

What is @temporal in hibernate?

The @Temporal annotation has the single parameter value of type TemporalType. It can be either DATE, TIME or TIMESTAMP, depending on the underlying SQL type that we want to use for the mapping.


1 Answers

Use the columnDefinition attribute of the @Column annotation:

@Column(name = "startTime", columnDefinition="DATETIME") @Temporal(TemporalType.TIMESTAMP) private Date startTime; 

And please, make your attributes private.

like image 190
JB Nizet Avatar answered Sep 18 '22 07:09

JB Nizet