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 数据库生成的属性值展示

  1. @Temporal(TemporalType.TIMESTAMP)
  2. @Column(insertable = false, updatable = false)
  3. @org.hibernate.annotations.Generated(
  4. org.hibernate.annotations.GenerationTime.ALWAYS
  5. )
  6. protected Date lastModified;
  7. @Column(insertable = false)
  8. @org.hibernate.annotations.ColumnDefault("1.00")
  9. @org.hibernate.annotations.Generated(
  10. org.hibernate.annotations.GenerationTime.INSERT
  11. )
  12. 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的兼容性例子。一个典型的 被创建于字段 一次保存的时候创建不被更新。

  1. @Temporal(TemporalType.TIMESTAMP)
  2. @Column(updatable = false)
  3. @org.hibernate.annotations.CreationTimestamp
  4. protected Date createdOn;
  5. // Java 8 API
  6. // protected Instant reviewedOn;

OK书本内容就是这样写的,下面看我们自己的需求和实现。

我们在定义JPA的entity时,有需要设置数据库时间戳的需求,一般情况下,会有一个字段需求记录创建时间,一个字段记录更新时间。那么在hibernate配置中是如何操作的呢?

看如下:

  1. @Entity
  2. @Table(name="RS_SIGNUPUSER")
  3. public class RsSignUpUser {
  4. @Id
  5. @GenericGenerator(name="UUIDGENERATE",strategy="uuid2")
  6. @GeneratedValue(generator="UUIDGENERATE")
  7. @Column(name="ID",length=36)
  8. private String ID;
  9. @Temporal(TemporalType.TIMESTAMP)
  10. @Column(updatable = false)
  11. @org.hibernate.annotations.CreationTimestamp
  12. private Date CREATETIME;
  13. @Column(name="UPDATETIME")
  14. @org.hibernate.annotations.UpdateTimestamp
  15. @Temporal(TemporalType.TIMESTAMP)
  16. private Date UPDATETIME;

略去了getters和setters方法。

创建的时候

  1. EntityManager entityManager = entityManagerFactory.createEntityManager();
  2. entityManager.getTransaction().begin();
  3. entityManager.persist( new Event( "Our very first event!", new Date() ) );
  4. RsSignUpUser rsuu = new RsSignUpUser();
  5. rsuu.setUSERZYBM("1");
  6. rsuu.setZONECODE("1");
  7. entityManager.persist(rsuu);

睡眠一秒,更新

  1. entityManager.getTransaction().commit();
  2. entityManager.close();
  3.  
  4. // now lets pull events from the database and list them
  5. entityManager = entityManagerFactory.createEntityManager();
  6. entityManager.getTransaction().begin();
  7.  
  8. try {
  9. Thread.sleep(1000);
  10. } catch (InterruptedException e) {
  11. // TODO Auto-generated catch block
  12. e.printStackTrace();
  13. }
  14. List<RsSignUpUser> result1 = entityManager.createQuery( "from RsSignUpUser", RsSignUpUser.class ).getResultList();
  15. for ( RsSignUpUser event : result1 ) {
  16. event.setBZ("bb");
  17. }
  18. entityManager.getTransaction().commit();
  19. entityManager.close();

可以看到数据库的数值:


时间是存在的。当然也可以在数据库的定义中增加,但是目前发现hibernate自动生成的表结构中,不能生成表注释和字段注释啊,一大遗憾啊。

Hibernate设置时间戳的默认值和更新时间的自动更新的更多相关文章

  1. [转]Hibernate设置时间戳的默认值和更新时间的自动更新

    原文地址:http://blog.csdn.net/sushengmiyan/article/details/50360451 Generated and default property value ...

  2. SQLServer 2012 可视化窗口中,设置“时间”默认值为“当前时间"

    最近,需要在SQLServer 2012中,设置datetime的默认值为当前时间. 通过可视化窗口进行设置,而不是将getdate()函数写在sql语句中,也不是将‘2022-2-2 22:22:2 ...

  3. 设置easyui input默认值

    /*设置input 焦点*/ $(function () { //集体调用 $(".formTextBoxes input").each(function () { $(this) ...

  4. 二货Mysql中设置字段的默认值问题

    Mysql设置字段的默认值的确很落伍 1.不支持函数 2.只支持固定常量. 经常用到的日期类型,因为不支持getdate或者now函数,所以只能设置timestamp类型 而且还必须在默认值那个地方写 ...

  5. 设置Input标签Date默认值为当前时间

    需求:想设置Imput标签Date默认值为当前时间,通过JavaScript实现. <html> ...... <body> <input type="date ...

  6. mysql设置timpstamp的默认值为 '0000-00-00 00:00:00' 时报错

    问题:mysql设置timpstamp的默认值为 '0000-00-00 00:00:00' 时报错: ERROR 1067 (42000): Invalid default value for 'u ...

  7. Odoo14 设置Binary字段默认值

    1 # Odoo 中的附件也就是Binary字段都是经过特殊处理的 2 # 首先是上传的时候会进行base64编码后再上传到服务器 3 # 服务器进行压缩存放在odoo文件仓库中 4 # 每个odoo ...

  8. Atitit 热更新资源管理器 自动更新管理器 功能设计

    Atitit 热更新资源管理器 自动更新管理器 功能设计 · 多线程并行下载支持 · 两层进度统计信息:文件级以及字节级 · Zip压缩文件支持 · 断点续传 · 详细的错误报告 · 文件下载失败重试 ...

  9. ios开发 数据库版本迁移手动更新迭代和自动更新迭代

    数据库版本迁移顾名思义就是在原有的数据库中更新数据库,数据库中的数据保持不变对表的增.删.该.查. 数据持久化存储: plist文件(属性列表) preference(偏好设置) NSKeyedArc ...

随机推荐

  1. APP开发外包时常见的错误

    时代在发展,科技在进步,很多企业都想要开发出属于自己的一款APP.然而,不是每个企业都有开发团队或是专门雇一个技术人员来做的,有一个好方法就是把开发APP的工作外包出去,找一个比较好的外包公司根据自己 ...

  2. 用js来实现那些数据结构08(链表02-双向链表)

    其实无论在任何语言中,一种数据结构往往会有很多的延伸和变种以应对不同场景的需要.其实前面我们所学过的栈和队列也是可以用链表来实现的.有兴趣的小伙伴可以自己尝试着去实现以下. 有点跑题了...,我们还是 ...

  3. 【实验吧】CTF_Web_简单的SQL注入之1

    题目链接:http://ctf5.shiyanbar.com/423/web/ 简单的SQL注入之1,比2,3都简单一些.利用2 的查询语句也可以实现:1'/**/union/**/select/** ...

  4. [SDOI 2015]约数个数和

    Description  设d(x)为x的约数个数,给定N.M,求 $\sum^N_{i=1}\sum^M_{j=1}d(ij)$ Input 输入文件包含多组测试数据. 第一行,一个整数T,表示测试 ...

  5. [HNOI 2001]软件开发

    Description 某软件公司正在规划一项n天的软件开发计划,根据开发计划第i天需要ni个软件开发人员,为了提高软件开发人员的效率,公司给软件人员提供了很多的服务,其中一项服务就是要为每个开发人员 ...

  6. 【Codeforces Round 418】An impassioned circulation of affection DP

                                                            C. An impassioned circulation of affection   ...

  7. poj1741Tree 点分治

    上午学习了点分治,写了1个半小时终于写出一个代码--poj1741,可以说是个模板题. 分治:对于每个儿子找出重心,分别处理 注意:1.每次处理一个重心后,ans减去对它儿子的处理 原因:因为统计方法 ...

  8. Linux中LCD设备驱动-framebuffer(帧缓冲)【】

    转自:https://blog.csdn.net/linux_devices_driver/article/details/7079442 1.framebuffer 帧缓冲     帧缓冲(fram ...

  9. A neural chatbot using sequence to sequence model with attentional decoder. This is a fully functional chatbot.

    原项目链接:https://github.com/chiphuyen/stanford-tensorflow-tutorials/tree/master/assignments/chatbot 一个使 ...

  10. Cisco 的基本配置实例之四----vlan的规划及配置(接入交换机)

    4.2 接入交换机的相关配置 ## 在此例中,我们联入的是一台接入交换机,此交换机的gi0/1口上联至核心交换机.也就意味着我们需要配置gi0/1为trunk口.具体的配置如下: D-2960-3(c ...