开发者

Java: JPA classes, refactoring from Date to DateTime

开发者 https://www.devze.com 2022-12-31 22:21 出处:网络
With a table created using this SQL Create Table X ( ID varchar(4) Not Null, XDATE date ); and an entity class defined like so

With a table created using this 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 xDate attribute can only store dates, e.g. 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?


If you want to also store time information at the database level, use TemporalType.DATETIME:

@Column(name = "XDATE")
@Temporal(TemporalType.DATETIME)
private Date xDate; //java.util.Date

Use a TIMESTAMP column type at the database level (and xDate will be stored as 'yyyy-MM-dd HH:mm:ss.S').


Have you tried changing the @Temporal value 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消