ATP
ATP

Reputation: 862

Does Hibernate update handle DEFAULT CURRENT_TIMESTAMP SQL clause?

I have a MySQL table with three columns: id int(10), status varchar(10), created_on timestamp NULL DEFAULT CURRENT_TIMESTAMP. When I try to insert records manually in the table using INSERT INTO EMPLOYEE(status) VALUES('STATUS1') clause, it correctly populates the value of the created_on column as well.

But, when I try to insert records through Hibernate, the created_on column is not populated. It stays as NULL. I understand that my column currently allows null as I have not explicitly announced it to be not null, but my question is more concentrated on the hibernate side.

What can I do to make sure that the created_on column is populated automatically like that of my manual INSERT clause? Or this is the way hibernate is designed to work?

Here's my hibernate snippet:

    Transaction tx = session.beginTransaction();
    Employee employee = new Employee(status);
    session.save(employee);         
    tx.commit();

And following is the Hibernate configuration

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="status" column="status" type="string"/>
      <property name="created_on" column="created_on" type="date"/>
   </class>
</hibernate-mapping>

Upvotes: 1

Views: 678

Answers (1)

nickmesi
nickmesi

Reputation: 180

MySQL will insert default values only when the column is not specified in the insert query. According to your current mapping, hibernate will produce the following query:

insert 
into
    EMPLOYEE
    (status, created_on) 
values
    (?, ?)

Which will insert null to created_on column. To have the default CURRENT_TIMESTAMP by MySQL use insert="false" in your mapping.

 <property name="created_on" column="created_on" type="date" insert="false"/>

Upvotes: 4

Related Questions