我有一个包含三列的MySQL表:id int(10), status varchar(10), created_on timestamp NULL DEFAULT CURRENT_TIMESTAMP
。当我尝试使用INSERT INTO EMPLOYEE(status) VALUES('STATUS1')
子句在表中手动插入记录时,它也会正确填充created_on
列的值。
但是,当我尝试通过Hibernate插入记录时,不会填充created_on
列。它保持为NULL。我知道我的列目前允许null,因为我没有明确宣布它不为null,但我的问题更集中在hibernate方面。
我该怎样做才能确保created_on
列自动填充,就像我的手动INSERT
子句一样?或者这是hibernate设计的工作方式?
这是我的hibernate代码段:
Transaction tx = session.beginTransaction();
Employee employee = new Employee(status);
session.save(employee);
tx.commit();
以下是Hibernate配置
<?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>
答案 0 :(得分:4)
只有在插入查询中未指定列时,MySQL才会插入默认值。根据您当前的映射,hibernate将生成以下查询:
insert
into
EMPLOYEE
(status, created_on)
values
(?, ?)
将向created_on
列插入null。要让MySQL使用默认CURRENT_TIMESTAMP
,请在映射中使用insert="false"
。
<property name="created_on" column="created_on" type="date" insert="false"/>