Home >Database >Mysql Tutorial >How to Store Java Date and Time in MySQL datetime Field Using JPA?
Storing Java Date into MySQL datetime with JPA
When attempting to store a Java Date into a MySQL datetime field, you may encounter an issue where only the date is preserved, while the time remains defaulted to 00:00:00. This is because the default mapping in JPA (using Hibernate) does not correctly handle the conversion.
To resolve this, you can convert the Java Date into a string in the desired format using SimpleDateFormat. For example:
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);
The resulting currentTime string can then be used to set the value of the datetime field:
// Assuming you have an entity with a datetime field named "contactUsTime" entity.setContactUsTime(currentTime);
This will correctly store both the date and time components in the MySQL database.
The above is the detailed content of How to Store Java Date and Time in MySQL datetime Field Using JPA?. For more information, please follow other related articles on the PHP Chinese website!