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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x