[转]Hibernate设置时间戳的默认值和更新时间的自动更新
原文地址:http://blog.csdn.net/sushengmiyan/article/details/50360451
Generated and default property values
生成的和默认的属性值
The database sometimes generates a property value, usually when you insert a row for the first time.
数据库通常会在第一次插入一条数据的时候产生一个属性值。
Examples of database-generated values are a creation timestamp, a default price for an item, and a trigger that runs for every modification.
数据库产生值得一个例子就是创建时的时间戳,物品的初始默认价格,以及每次修改时运行的触发器。
Typically, Hibernate applications need to refresh instances that contain any properties for which the database generates values, after saving.
典型的,HIbernate应用程序在保存之后需要刷新包含由数据库为其生成值的任何属性对象。
This means you would have to make another round trip to the database to read the value after inserting or updating a row.
这就意味着,你不得不进行另一次的数据库访问来读取插入或者更新一行数据之后的值。
Marking properties as generated, however, lets the application delegate this responsibility to Hibernate.
然而,把属性标识为已生成,就让应用程序把责任委托给了hibernate。
Essentially, whenever Hibernate issues an SQL INSERT or UPDATE for an entity that has declared generated properties, it does a SELECT immediately afterward to retrieve the generated values.
基本上,当hibernate为一个声明了已生成标识的属性的实体执行SQL插入或者更新的时候,它会立刻执行一个select来获取新生成的值。
You mark generated properties with the @org.hibernate.annotations.Generated annotation.
你使用注解@org.hibernate.annotations.Generated来标识一个已生成属性。
Listing 5.4 Database-generated property values
代码清单5.4 数据库生成的属性值展示
- @Temporal(TemporalType.TIMESTAMP)
- @Column(insertable = false, updatable = false)
- @org.hibernate.annotations.Generated(
- org.hibernate.annotations.GenerationTime.ALWAYS
- )
- protected Date lastModified;
- @Column(insertable = false)
- @org.hibernate.annotations.ColumnDefault("1.00")
- @org.hibernate.annotations.Generated(
- org.hibernate.annotations.GenerationTime.INSERT
- )
- protected BigDecimal initialPrice;
Available settings for GenerationTime are ALWAYS and INSERT.
GenerationTime的可用的设置选项是ALWAYS和INSERT。
With ALWAYS, Hibernate refreshes the entity instance after every SQL UPDATE or INSERT.
当使用ALWAYS的时候,Hibernate每次执行SQL UPADATE或者INSERT插入的时候就会刷新实体。
The example assumes that a database trigger will keep the lastModified property current.
例子假定数据库的触发器能保持让lastModified属性保持是当前时间。
The property should also be marked read-only, with the updatable and insertable parameters of @Column.
属性也应该标识为只读,只读属性使用注解@Column的updatable和insertable来实现。
If
both are set to false, the property’s column(s) never appear in the
INSERT or UPDATE statements, and you let the database generate the
value.
如果两个都设置了false,属性列表就用于不会在INSERT或者UPADATE语句中出现了,这些列的数值就由数据库来产生值咯。
With GenerationTime.INSERT, refreshing only occurs after an SQL INSERT, to retrieve the default value provided by the database.
使用GenerationTime.INSERT,只会在SQL INSERT的时候出现,来获取数据库的默认值。
Hibernate also maps the property as not insertable. hibernate也会映射为属性不可插入。
The
@ColumnDefault Hibernate annotation sets the default value of the
column when Hibernate exports and generates the SQL schema DDL.
@ColumnDefault属性注解,设置列表的默认属性,当hibernate导出和生成SQL schenma DDL的时候。
Timestamps
are frequently automatically generated values, either by the
database,as in the previous example, or by the application. Let’s have a
closer look at the @Temporal annotation you saw in listing 5.4.
Timestamps是自动生成值中经常使用的,或者是通过数据库产生,如之前的例子,或者是通过应用程序生成,可以通过仔细观看下面代码清单5.4中的注解。
The
lastModified property of the last example was of type java.util.Date,
and a database trigger on SQL INSERT generated its value.
在、上个例子的java.utia.Date类型中的 lastModifiied属性和数据库的SQL INSERT触发器产生值。
The JPA specification requires that you annotate temporal properties with @Temporal to declare the accuracy of the
SQL data type of the mapped column.
JPA规范要求使用@Temporal注解来声明映射的SQL数据类型。
The Java temporal types are java.util.Date,java.util.Calendar, java.sql.Date, java.sql.Time, and java.sql.Timestamp.
java类型有如下java.util.Date,java.util.Calendar, java.sql.Date, java.sql.Time, and java.sql.Timestamp。
Hibernate
also supports the classes of the java.time package available in JDK 8.
(Actually, the annotation isn’t required if a converter is applied or
applicable for the property.You’ll see converters again later in this chapter.)
hibernate也提供JDK8中的java.time包。(实际上如果使用了converter转换器之后,注解是不需要了。在下一节会看在次看到转换器)
The
next listing shows a JPA-compliant example: a typical “this item was
created on” timestamp property that is saved once but never updated.
下一个代码清单展示一个JPA的兼容性例子。一个典型的 被创建于字段 一次保存的时候创建不被更新。
- @Temporal(TemporalType.TIMESTAMP)
- @Column(updatable = false)
- @org.hibernate.annotations.CreationTimestamp
- protected Date createdOn;
- // Java 8 API
- // protected Instant reviewedOn;
OK书本内容就是这样写的,下面看我们自己的需求和实现。
我们在定义JPA的entity时,有需要设置数据库时间戳的需求,一般情况下,会有一个字段需求记录创建时间,一个字段记录更新时间。那么在hibernate配置中是如何操作的呢?
看如下:
- @Entity
- @Table(name="RS_SIGNUPUSER")
- public class RsSignUpUser {
- @Id
- @GenericGenerator(name="UUIDGENERATE",strategy="uuid2")
- @GeneratedValue(generator="UUIDGENERATE")
- @Column(name="ID",length=36)
- private String ID;
- @Temporal(TemporalType.TIMESTAMP)
- @Column(updatable = false)
- @org.hibernate.annotations.CreationTimestamp
- private Date CREATETIME;
- @Column(name="UPDATETIME")
- @org.hibernate.annotations.UpdateTimestamp
- @Temporal(TemporalType.TIMESTAMP)
- private Date UPDATETIME;
略去了getters和setters方法。
创建的时候
- EntityManager entityManager = entityManagerFactory.createEntityManager();
- entityManager.getTransaction().begin();
- entityManager.persist( new Event( "Our very first event!", new Date() ) );
- RsSignUpUser rsuu = new RsSignUpUser();
- rsuu.setUSERZYBM("1");
- rsuu.setZONECODE("1");
- entityManager.persist(rsuu);
睡眠一秒,更新
- entityManager.getTransaction().commit();
- entityManager.close();
- // now lets pull events from the database and list them
- entityManager = entityManagerFactory.createEntityManager();
- entityManager.getTransaction().begin();
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- List<RsSignUpUser> result1 = entityManager.createQuery( "from RsSignUpUser", RsSignUpUser.class ).getResultList();
- for ( RsSignUpUser event : result1 ) {
- event.setBZ("bb");
- }
- entityManager.getTransaction().commit();
- entityManager.close();
可以看到数据库的数值:
时间是存在的。当然也可以在数据库的定义中增加,但是目前发现hibernate自动生成的表结构中,不能生成表注释和字段注释啊,一大遗憾啊。
[转]Hibernate设置时间戳的默认值和更新时间的自动更新的更多相关文章
- Hibernate设置时间戳的默认值和更新时间的自动更新
Generated and default property values 生成的和默认的属性值 The database sometimes generates a property value, ...
- SQLServer 2012 可视化窗口中,设置“时间”默认值为“当前时间"
最近,需要在SQLServer 2012中,设置datetime的默认值为当前时间. 通过可视化窗口进行设置,而不是将getdate()函数写在sql语句中,也不是将‘2022-2-2 22:22:2 ...
- 设置easyui input默认值
/*设置input 焦点*/ $(function () { //集体调用 $(".formTextBoxes input").each(function () { $(this) ...
- 二货Mysql中设置字段的默认值问题
Mysql设置字段的默认值的确很落伍 1.不支持函数 2.只支持固定常量. 经常用到的日期类型,因为不支持getdate或者now函数,所以只能设置timestamp类型 而且还必须在默认值那个地方写 ...
- 设置Input标签Date默认值为当前时间
需求:想设置Imput标签Date默认值为当前时间,通过JavaScript实现. <html> ...... <body> <input type="date ...
- mysql设置timpstamp的默认值为 '0000-00-00 00:00:00' 时报错
问题:mysql设置timpstamp的默认值为 '0000-00-00 00:00:00' 时报错: ERROR 1067 (42000): Invalid default value for 'u ...
- Odoo14 设置Binary字段默认值
1 # Odoo 中的附件也就是Binary字段都是经过特殊处理的 2 # 首先是上传的时候会进行base64编码后再上传到服务器 3 # 服务器进行压缩存放在odoo文件仓库中 4 # 每个odoo ...
- mysql升级到5.7时间戳(timestamp)默认值报错
原文:mysql升级到5.7时间戳报错 往数据库里创建新表的时候报错: [Err] 1067 - Invalid default value for 'updateTime' DROP TABLE I ...
- SQL SERVER 2008 设置字段默认值为当前时间
在某些情况下需要对某条记录添加上时间戳,比如用户注册,需要记录用户的注册时间,在SQL SERVER 2008中可以通过 1. 添加新字段 2. 数据类型设置为smalldatetime 3. 默认值 ...
随机推荐
- 三维网格细分算法(Catmull-Clark subdivision & Loop subdivision)附源码
下图描述了细分的基本思想,每次细分都是在每条边上插入一个新的顶点,可以看到随着细分次数的增加,折线逐渐变成一条光滑的曲线.曲面细分需要有几何规则和拓扑规则,几何规则用于计算新顶点的位置,拓扑规则用于确 ...
- shiro和quartz同时存在于项目中,解决冲突的方案
shiro自带了quartz定时任务,不过版本是1.3的 很多项目都会使用shiro,另外定时任务也会使用,quartz的版本2.2目前和shiro不兼容 有人通过修改源码可以解决 我这边是这样解决的 ...
- 第14章 位图和位块传输_14.4 GDI位图对象(3)
14.4.10 非矩形的位图图像 (1)“掩码”位图——单色位图,要显示的像素对应的掩码置1,不显示置0(2)光栅操作(点这里,见此文分析) (3)MaskBlt函数 ①MaskBlt(hdcDest ...
- python的高级特性3:神奇的__call__与返回函数
__call__是一个很神奇的特性,只要某个类型中有__call__方法,,我们可以把这个类型的对象当作函数来使用. 也许说的比较抽象,举个例子就会明白. In [107]: f = abs In [ ...
- 配置Tomcat使用Redis作为session管理
1. 在 tomcat/lib 中增加以下jar包 commons-pool2-.jar jedis-.jar tomcat-redis-session-manager-.jar 2. 修改tomca ...
- ACA烤箱菜单各项温度
说明书找不到了, 网上找到的各项温度说明, 记一个备用 casserole 218度 cake 171度 backery 177度 frozen food 238度 patato 232度 roast ...
- css position, display, float 内联元素、块级元素
position属性:position属性指出一个元素的定位方法.有4种可能值:static, relative, absolute or fixed: static:默认值,元素按照在文档流中出现的 ...
- xhEditor用法
xhEditor是一个基于jQuery开发的简单迷你并且高效的在线可视化HTML编辑器,而且兼容很多浏览器,所以就选它了,具体使用如下: 1 .下载xhEditor 最新版本 下载地址:http:// ...
- .net混淆、反编译工具调查
常用的工具列表[比较常见的] 混淆器.加密 Dotfuscator VS默认带的工具,不过是个社区版 强度不大 dotNET Reactor 使用了NativeCode 和混淆的形式 Xenocode ...
- .NET MVC控制器分离到类库的方法
在.ASP.NET MVC的开发中,我们创建完项目之后,ASP.NET MVC是已Model-Controller-View的形式存在的,在创建项目自动生成的内容上Model我们很容易分离成类库,所以 ...