Home > Database > Mysql Tutorial > How to Store Java Date and Time in MySQL datetime Field Using JPA?

How to Store Java Date and Time in MySQL datetime Field Using JPA?

Susan Sarandon
Release: 2024-12-05 16:40:11
Original
173 people have browsed it

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template