简体   繁体   English

如何使用Hibernate注释将Java日期映射到mysql中的DATETIME(默认情况下为TIMESTAMP)

[英]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. 我的所有数据库表都应该有一个endTime字段,默认情况下应该是END_OF_TIME或类似的东西。 I am not happy about the 2038 limitation so I want endTime to be of type DATETIME in mysql. 我对2038的限制不满意所以我希望endTime在mysql中的类型为DATETIME。

My Java code is: 我的Java代码是:

@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? 我可以通过使用DATETIME类型的endTime字段手动创建表,然后将实体endTime映射到该列,但是我希望Hibernate自动生成表 - 我该怎么做?

Use the columnDefinition attribute of the @Column annotation : 使用@Column批注columnDefinition属性:

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

And please, make your attributes private. 请将您的属性设为私有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM