Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Losing Time When Saving to Database

I'm using Java and hibernate on a web server to save to an Oracle SQL database. I create a Java Date object, but for some reason by the time it makes it to the database, it only has the date and not the time. For instance, the Date object will say "Dec 10, 2012 1:23:45 PM" but in the database it only says "10-DEC-12"

Any idea why this would happen? Below is an example of how the date is created and saved.

service.java

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

Nos nos = new Nos();
nos.setTimeReceived( new Date() );
session.save( nos );

tx.commit();

Nos.java

@Entity
@Table(name = "nos")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Nos
{
    @Id
    @GeneratedValue
    private Long id;

    @Basic(optional=false)
    @Temporal(TemporalType.DATE)
    @Column(name="timereceived")
    private java.util.Date timeReceived;

// getters and setters
like image 480
Jesse Jashinsky Avatar asked Dec 27 '22 13:12

Jesse Jashinsky


1 Answers

Use TemporalType.TIMESTAMP, which corresponds to a java.sql.Timestamp.

As per the TemporalType JavaDocs, TemporalType.DATE maps to a java.sql.Date, which as you're seeing as no time component:

To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

like image 144
Matt Ball Avatar answered Dec 30 '22 10:12

Matt Ball