# Hibernate设置时间戳的默认值和更新时间的自动更新

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.

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.

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.

You mark generated properties with the @org.hibernate.annotations.Generated annotation.

Listing 5.4 Database-generated property values

@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.

The example assumes that a database trigger will keep the lastModified property current.

The property should also be marked read-only, with the updatable and insertable parameters of @Column.

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.

With GenerationTime.INSERT, refreshing only occurs after an SQL INSERT, to retrieve the default value provided by the database.

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.

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.

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

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

@Entity
@Table(name="RS_SIGNUPUSER")
@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;


		EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist( new Event( "Our very first event!", new Date() ) );
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 {
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for ( RsSignUpUser event : result1 ) {
event.setBZ("bb");
}
entityManager.getTransaction().commit();
entityManager.close();