Storing milliseconds in MySQL timestamp column using Hibernate
Asked Answered
C

3

6

I'm trying to store a java Date with milliseconds in MySQL's timestamp column using Hibernate, but the millisecods are stored always as .000.

The definition of the column in hibernate is as follows:

@Type(type="timestamp")``
private Timestamp timestamp;

In DB the column is declared as TIMESTAMP(3)

I've tried different combinations, including Date, but neither helped. I use MySQL 5.6.25, Connector/J version 5.1.37, Hibernate 4.0.1.

I've been investigating it for a while, but still couldn't find any solution that works form me.

ANy help will be appreciated.

Charissa answered 17/1, 2016 at 13:37 Comment(1)
I have the same issue, did you solve it?Copley
M
0

Have you tried using DATETIME(3) or TIMESTAMP(4)? I believe both of these will give you the milliseconds. If you are trying to get the millisecond time where the interatction happens such as the row becomes updated you can use ON UPDATE DATETIME(3)

Merl answered 7/12, 2016 at 16:12 Comment(0)
S
0

It seems that Hibernate and MySql interaction removes de milliseconds precision of your Date/Timestamp Java property. I have the same problem.

My solution is to "hack" hibernate telling that the entity property is an string and then serializing/deserializing the value in the setter/getter

@Column(name="time")
private String time
...
public Date getTime(){
  return strTodate( this.time );
}
public void setTime(Date value){
  this.time = dateToStr( value );
}

When MySQL receives an String for a Datetime(3) column, string is properly converted and milliseconds are not lost :-)

Fortunately, when reading from MySQL, Datetime(3) is propery serialized to string without milliseconds lost

The string date format used is "yyyy-MM-dd hh:mm:ss.SSS"

The idea of this solution is, don't let hibernate deal with dates. Delegate the responsability to MySql.

Unfortunatelly, MySQL doesn't accept an standard ISO string (i.e.: "yyyy-MM-ddThh:mm:ss.SSSZ") and this solution is not compatible with postgres (string date format is not the same)

Selfcommand answered 21/11, 2022 at 12:2 Comment(0)
L
0

I have just encountered the problem, and the solution was to change the JDBC driver from com.mysql:mysql-connector-j:8.0.31 to org.mariadb.jdbc:mariadb-java-client:3.3.1.

If you do that, do not forget to change your JDBC URLs from jdbc:mysql:... to jdbc:mariadb:....

Latrena answered 12/12, 2023 at 23:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.