hibernate配置自动插入当前时间

http://blog.sina.com.cn/s/blog_4b5bc01101016lmo.html

用户注册的时候,注册时间应该是由数据库自动生成的,怎样通过Hibernate配置生成这个默认时间呢?

<?xmlversion="1.0"?>

<!DOCTYPEhibernate-mappingPUBLIC

"-//Hibernate/HibernateMappingDTD3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mappingpackage="com.mine.dto.model">

<classname="User"table="users">

<idname="id"column="ID"type="integer"unsaved-value="null">

<generatorclass="native"/>

</id>

<propertyname="userName"column="USERNAME"unique="true"

length="40"/>

<propertyname="nickName"column="NICKNAME"length="20"/>

<propertyname="password"column="PASSWORD"length="20"/>

<propertyname="rePassword"column="REPASSWORD"length="20"/>

<propertyname="sex"column="SEX"length="10"/>

<propertyname="birthday"column="BIRTHDAY"type="date"/>

<propertyname="registerDate"generated="insert"not-null="true">

<columnname="REGISTERDATE"sql-type="timestamp"default="CURRENT_TIMESTAMP"/>

</property>

<propertyname="email"column="EMAIL"length="30"/>

<propertyname="address"column="ADDRESS"length="100"/>

</class>

</hibernate-mapping>

其中的

……

<propertyname="registerDate"generated="insert"not-null="true">

<columnname="REGISTERDATE"sql-type="timestamp"default="CURRENT_TIMESTAMP"/>

</property>

……

generated有三个可选值:

never(默认)表明此属性不是从数据库生成的

insert表明此属性在insert的时候生成,但是不会在随后的update时从新生成

always表明此属性在insert时或者update时都被生成

sql-type指生成的时间的类型

defaultHibernate本身提供current_date,current_timestamp和current_time三种函数

DTO类如下:

packagecom.mine.dto.model;

importjava.sql.Timestamp;

importjava.util.Date;

publicclassUser{

privateIntegerid;

privateStringuserName;

privateStringnickName;

privateStringpassword;

privateStringrePassword;

privateStringsex;

privateDatebirthday;

privateTimestampregisterDate;

privateStringemail;

privateStringaddress;

publicUser(){}

//getter和setter略

}

运行

packagecom.mine.DB;

importorg.hibernate.cfg.Configuration;

importorg.hibernate.tool.hbm2ddl.SchemaExport;

publicclassExportDB{

publicstaticvoidmain(String[]args){

Configurationcfg=newConfiguration().configure();

SchemaExportexport=newSchemaExport(cfg);

export.create(true,true);

}

}

生成的sql代码:

droptableifexistsusers

createtableusers(

IDintegernotnullauto_increment,

USERNAMEvarchar(40)unique,

NICKNAMEvarchar(20),

PASSWORDvarchar(20),

REPASSWORDvarchar(20),

SEXvarchar(10),

BIRTHDAYdate,

REGISTERDATEtimestampdefaultCURRENT_TIMESTAMP,

EMAILvarchar(30),

ADDRESSvarchar(100),

primarykey(ID)

)

相关推荐