项目中,通常在数据库中会记录该条目的建立时间,以及后续该条目被更新的时间。建立时间即插入数据库记录的时间,以后条目被update时不会更新,更新时间则在每次update时都会更新。那么,在hibernate中怎么达到这一目的呢。
实测如下方法可行:
假设我有一个bean名为
imgFile,对应的数据库表为t_imgfile
其中create_time表示建立时间,对应bean的属性是createTime
update_time表示更新时间,对应bean的属性是updateTime
xx.hbm.xml中应以下设置
update
=
"false"表示在update时不更新,
insert
=
"true"表示在插入时须要更新:
- < property name = "createTime" update = "false" insert = "true" >
- < column name = "create_time" sql-type = "timestamp" default = "CURRENT_TIMESTAMP" />
- </ property>
- < property name = "updateTime" update = "true" insert = "true" >
- < column name = "update_time" sql-type = "timestamp" default = "CURRENT_TIMESTAMP" />
- </ property>
插入数据库前,程序里需对bean进行赋值,将这两个值set为当前时间以下
- imgFile.setCreateTime(new Timestamp(System.currentTimeMillis()));
- imgFile.setUpdateTime(new Timestamp(System.currentTimeMillis()));