Java:JPA 类,从 Date 重构到 DateTime
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2913729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: JPA classes, refactoring from Date to DateTime
提问by bguiz
With a table created using this SQL
使用此 SQL 创建的表
Create Table X (
ID varchar(4) Not Null,
XDATE date
);
and an entity class defined like so
和一个像这样定义的实体类
@Entity
@Table(name = "X")
public class X implements Serializable {
@Id
@Basic(optional = false)
@Column(name = "ID", nullable = false, length = 4)
private String id;
@Column(name = "XDATE")
@Temporal(TemporalType.DATE)
private Date xDate; //java.util.Date
...
}
With the above, I can use JPA to achieve object relational mapping. However, the xDateattribute can only store dates, e.g. dd/MM/yyyy.
有了上面的,我就可以用JPA来实现对象关系映射了。但是,该xDate属性只能存储日期,例如dd/MM/yyyy.
How do I refactor the above to store a full date object using just one field, i.e. dd/MM/yyyy HH24:mm?
如何重构上述内容以仅使用一个字段存储完整日期对象,即dd/MM/yyyy HH24:mm?
采纳答案by sblundy
Have you tried changing the @Temporalvalue to TemporalType.DATETIME? java.util.Date and java.sql.Date both store date and time components, the TemporalType controls which part JPA stored/pays attention to; date, time, or both.
您是否尝试将@Temporal值更改为TemporalType.DATETIME?java.util.Date 和 java.sql.Date 都存储日期和时间组件,TemporalType 控制 JPA 存储/关注哪一部分;日期、时间或两者。
回答by Pascal Thivent
If you want to also store time information at the database level, use TemporalType.DATETIME:
如果您还想在数据库级别存储时间信息,请使用TemporalType.DATETIME:
@Column(name = "XDATE")
@Temporal(TemporalType.DATETIME)
private Date xDate; //java.util.Date
Use a TIMESTAMPcolumn type at the database level (and xDatewill be stored as 'yyyy-MM-dd HH:mm:ss.S').
TIMESTAMP在数据库级别使用列类型(并将xDate存储为'yyyy-MM-dd HH:mm:ss.S')。

