Save java.util.Date file in MySQL database with millisecond accuracy

I would like to get millisecond accuracy in my MariaDB. After some research, I found that I needed to change columnDefinition, so I did this in my essence:

@NotNull
@Column(name = "createdDate", columnDefinition = "DATETIME(3) NOT NULL")
@Temporal(TemporalType.TIMESTAMP)
private TimeStamp createdDate;

@PrePersist
void onPersist() {
    createdDate = new Timestamp(new Date().getTime());
}

As a result of SQL to create the column:

`createdDate` DATETIME(3) NOT NULL

Now the value in the database is really 3 decimal places:

2016-09-12 16:57:44.000

... but they are always 000

What have I done wrong or what have I forgotten?

Edit: I tried without JAVA:

CREATE TABLE `test` (
    `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
    `createdDate` DATETIME(3) NOT NULL,
    PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;

And then:

INSERT INTO test (createdDate)
VALUES(current_timestamp())

Result:

2016-09-13 13:57:44.000
+4
source share
3 answers

Your problem is most likely due to the fact that you are mixing dates and timestamps. Changing type createdDateto java.sql.Timestampshould solve your problem.

, MySQL 5.6.4, DateTime .

OP:

Java , :

createdDate = new Timestamp(new Date().getTime());

createdDate = new Timestamp(System.currentTimeInMilliseconds()); ?

, JodaTime, , , :)

, , Timestamp DB Datetime, , Datetime .

: Oracle Date API:

Date()
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

System.currentTimeInMilliseconds() - .

, SQL ( Java) CURRENT_TIMESTAMP, , . , Java . . , .

+2

MariaDB . org.joda.DateTime java.util.time. .

, MySQL Connector MariaDB/J JDBC.

MariaDB MySQL Connector , . , Hibernate Connector , , . , MySQL MariaDB. , , , .

+1

To do this, use pure JPA:

@Column(name="STMP", columnDefinition = "TIMESTAMP (6)")
private Timestamp timestamp = Timestamp.from(Instant.now());
0
source

Source: https://habr.com/ru/post/1654432/


All Articles