日期:2014-05-16 浏览次数:20934 次
?
用户注册的时候,注册时间应该是由数据库自动生成的,怎样通过Hibernate配置生成这个默认时间呢?
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.mine.dto.model"> <class name="User" table="users"> <id name="id" column="ID" type="integer" unsaved-value="null"> <generator class="native" /> </id> <property name="userName" column="USERNAME" unique="true" length="40" /> <property name="nickName" column="NICKNAME" length="20" /> <property name="password" column="PASSWORD" length="20" /> <property name="rePassword" column="REPASSWORD" length="20" /> <property name="sex" column="SEX" length="10" /> <property name="birthday" column="BIRTHDAY" type="date" /> <property name="registerDate" generated="insert" not-null="true"> <column name="REGISTERDATE" sql-type="timestamp" default="CURRENT_TIMESTAMP" /> </property> <property name="email" column="EMAIL" length="30" /> <property name="address" column="ADDRESS" length="100" /> </class> </hibernate-mapping>
?
?其中的
…… <property name="registerDate" generated="insert" not-null="true"> <column name="REGISTERDATE" sql-type="timestamp" default="CURRENT_TIMESTAMP" /> </property> ……
? generated有三个可选值:
never(默认) 表明此属性不是从数据库生成的
?? ? ?insert ?表明此属性在insert的时候生成,但是不会在随后的update时从新生成
?? ? ?always ?表明此属性在insert时或者update时都被生成
?
??sql-type ?指生成的时间的类型
?
??default Hibernate本身提供current_date,current_timestamp和current_time三种函数
?
DTO 类如下:
?
package com.mine.dto.model; import java.sql.Timestamp; import java.util.Date; public class User { private Integer id; private String userName; private String nickName; private String password; private String rePassword; private String sex; private Date birthday; private Timestamp registerDate; private String email; private String address; public User() {} // getter和setter略 }
?
?
运行
package com.mine.DB; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class ExportDB { public static void main(String[] args) { Configuration cfg = new Configuration().configure(); SchemaExport export = new SchemaExport(cfg); export.create(true, true); } }
?生成的sql代码:
?
drop table if exists users create table users ( ID integer not null auto_increment, USERNAME varchar(40) unique, NICKNAME varchar(20), PASSWORD varchar(20), REPASSWORD varchar(20), SEX varchar(10), BIRTHDAY date, REGISTERDATE timestamp default CURRENT_TIMESTAMP, EMAIL varchar(30), ADDRESS varchar(100), primary key (ID) )
? 参考的这个