简体   繁体   中英

Using hibernate UPDATE column of type “datetime” for mysql

I am using Hibernate for ORM mapping. One of the tables has a column of type "datetime". The column in question needs to be updated with "current-time" (time of data insertion). I am aware that I can use the date() function as the default value. I would rather prefer setting the timestamp when I set other attributes of the object.

Question 1) What is the equivalent of SQL date() function in Java?

With mysql you can set an on update change : http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html

CREATE TABLE t1 (
  ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

The attribut will be updated with the current timestamp of the DB.

(you are lucky because it doesn't work with oracle ... (and I am with oracle ...) )

The equivalent of SQL date() in java is simply new Date() , eg:

myEntity.setDateField(new Date());

will set dateField to the current date and time.

I am trying in my code:

myEntity.setdDateCreated(new Date());

In hibernate mapping ->

property name="dateCreated" column="date_created" type="timestamp"

But in mysql it is saving as '0000-00-00 00:00:00'

Any guess why this is happening?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM