[java] How to store Java Date to Mysql datetime with JPA

Can any body tell me how can I store Java Date to Mysql datetime...?

When I am trying to do so...only date is stored and time remain 00:00:00 in Mysql date stores like this...

2009-09-22 00:00:00

I want not only date but also time...like

2009-09-22 08:08:11

I am using JPA(Hibernate) with spring mydomain classes uses java.util.Date but i have created tables using handwritten queries...

this is my create statement

CREATE TABLE ContactUs (
  id BIGINT AUTO_INCREMENT, 
  userName VARCHAR(30), 
  email VARCHAR(50),
  subject VARCHAR(100), 
  message VARCHAR(1024), 
  messageType VARCHAR(15), 
  contactUsTime DATETIME,
  PRIMARY KEY(id)
);

This question is related to java mysql datetime jpa

The answer is


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.


it works for me !!

in mysql table

DATETIME

in entity:

private Date startDate;

in process:

objectEntity.setStartDate(new Date());

in preparedStatement:

pstm.setDate(9, new java.sql.Date(objEntity.getStartDate().getTime()));

you will get 2011-07-18 + time format

long timeNow = Calendar.getInstance().getTimeInMillis();
java.sql.Timestamp ts = new java.sql.Timestamp(timeNow);
...
preparedStatement.setTimestamp(TIME_COL_INDEX, ts);

java.util.Date date = new Date();
Object param = new java.sql.Timestamp(date.getTime());    
preparedStatement.setObject(param);

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.


Probably because your java date has a different format from mysql format (YYYY-MM-DD HH:MM:SS)

do this

 DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
 Date date = new Date();
 System.out.println(dateFormat.format(date));

Use the following code to insert the date into MySQL. Instead of changing our date's format to meet MySql's requirement, we can help data base to recognize our date by setting the STR_TO_DATE(?, '%l:%i %p') parameters.

For example, 2014-03-12 can be represented as STR_TO_DATE('2014-03-12', '%Y-%m-%d')

preparedStatement = connect.prepareStatement("INSERT INTO test.msft VALUES (default, STR_TO_DATE( ?, '%m/%d/%Y'), STR_TO_DATE(?, '%l:%i %p'),?,?,?,?,?)"); 

Actually you may not use SimpleDateFormat, you can use something like this;

  @JsonSerialize(using=JsonDateSerializer.class)
  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
  private Date blkDate;

This way you can directly get the date with format as specified.


Its very simple though conditions in this answer are in mysql the column datatype is datetime and you want to send data from java code to mysql:

java.util.Date dt = new java.util.Date();
whatever your code object may be.setDateTime(dt);

important thing is just pick the date and its format is already as per mysql format and send it, no further modifications required.


I still prefer the method in one line

new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())

mysql datetime -> GregorianCalendar

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse("2012-12-13 14:54:30"); // mysql datetime format
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
System.out.println(calendar.getTime());

GregorianCalendar -> mysql datetime

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = format.format(calendar.getTime());
System.out.println(string);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to jpa

No converter found capable of converting from type to type How does spring.jpa.hibernate.ddl-auto property exactly work in Spring? Deserialize Java 8 LocalDateTime with JacksonMapper Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed How to beautifully update a JPA entity in Spring Data? JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory How to return a custom object from a Spring Data JPA GROUP BY query How to find distinct rows with field in list using JPA and Spring? What is this spring.jpa.open-in-view=true property in Spring Boot? Spring Data JPA and Exists query