hibernate中创建时间、更新时间字段的配置

来源:互联网 发布:js 时间戳格式化日期 编辑:程序博客网 时间:2024/06/06 09:54
项目中,一般在数据库中会记录该条目的创建时间,以及后续该条目被更新的时间。创建时间即插入数据库记录的时间,之后条目被update时不会更新,更新时间则在每次update时都会更新。那么,在hibernate中怎么达到这一目的呢。

实测以下方法可行:
假设我有一个bean名为imgFile,对应的数据库表为t_imgfile
其中create_time表示创建时间,对应bean的属性是createTime
update_time表示更新时间,对应bean的属性是updateTime

xx.hbm.xml中应如下设置
update = "false"表示在update时不更新,insert = "true"表示在插入时需要更新
[html] view plain copy
  1.         < property name = "createTime" update = "false" insert = "true" >    
  2.             < column name = "create_time" sql-type = "timestamp" default = "CURRENT_TIMESTAMP" />    
  3.         </ property>  
  4.        < property name = "updateTime" update = "true" insert = "true" >    
  5.             < column name = "update_time" sql-type = "timestamp" default = "CURRENT_TIMESTAMP" />    
  6.         </ property>  



插入数据库前,程序里需对bean进行赋值,将这两个值set为当前时间如下
[java] view plain copy
  1. imgFile.setCreateTime(new Timestamp(System.currentTimeMillis()));  
  2. imgFile.setUpdateTime(new Timestamp(System.currentTimeMillis()));  
0 0