views:

222

answers:

2

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?

+1  A: 

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.

sblundy
@sblundy : Thanks for the answer, that was my gut feel too, however, do I need to change the member variable in my entity class, or the schema definition for the table?
bguiz
@bguiz : Field no, column yes. It depends on which DB you're using, but DATETIME should work
sblundy
@sblundy : I'm using Toplink / JavaDB
bguiz
@bguiz : TIMESTAMP. Here's the relevent manual page http://db.apache.org/derby/docs/dev/ref/ref-single.html#crefsqlj31068
sblundy
@sblundy: java.sql.Date does *not* store a time component.
mtpettyp
bguiz
+2  A: 

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').

Pascal Thivent
+1 @Pascal Thivent : Thanks for the answer, both of you were right, but I'm giving the check to sblundy since he was first in.
bguiz
@bguiz Sure, no problem!
Pascal Thivent