How to store Java Date to Mysql datetime with JPA How to store Java Date to Mysql datetime with JPA mysql mysql

How to store Java Date to Mysql datetime with JPA


see in the link :

http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion

The following code just solved the problem:

java.util.Date dt = new java.util.Date();java.text.SimpleDateFormat sdf =      new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String currentTime = sdf.format(dt);

This 'currentTime' was inserted into the column whose type was DateTime and it was successful.


Annotate your field (or getter) with @Temporal(TemporalType.TIMESTAMP), like this:

public class MyEntity {    ...    @Temporal(TemporalType.TIMESTAMP)    private java.util.Date myDate;    ...}

That should do the trick.


Are you perhaps using java.sql.Date? While that has millisecond granularity as a Java class (it is a subclass of java.util.Date, bad design decision), it will be interpreted by the JDBC driver as a date without a time component. You have to use java.sql.Timestamp instead.