Hibernate sets the default value of the timestamp and the automatic update time.

Source: Internet
Author: User

Hibernate sets the default value of the timestamp and the automatic update time.

Generated and default property values

Generated and default attribute values

The database sometimes generates a property value, usually when you insert a row for the first time.

A database usually generates a property value when a data entry is inserted 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.

An example of database creation is the timestamp at creation, the initial default price of the item, and the trigger that runs at each modification.

Typically, Hibernate applications need to refresh instances that contain any properties for which the database generates values, after saving.

Typically, a HIbernate application needs to refresh any property object that contains the value generated by the database after it is saved.

This means you wowould have to make another round trip to the database to read the value after inserting or updating a row.

This means that you have to perform another database access to read the value after inserting or updating a row of data.

Marking properties as generated, however, lets the application delegate this responsibility to Hibernate.

However, if the property is identified as generated, the application is entrusted with hibernate.

Essential, 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.

Basically, when hibernate executes SQL insert or update for an object that declares an attribute with generated identifiers, it immediately executes a select statement to obtain the new value.

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

You use annotation @ org. hibernate. annotations. Generated to identify a Generated property.

Listing 5.4 Database-generated property values

Code List 5.4 display of database generated attribute 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.
The available setting options for GenerationTime are ALWAYS and INSERT.

 

With ALWAYS, Hibernate refreshes the entity instance after every SQL UPDATE or INSERT.

When using ALWAYS, every time Hibernate executes SQL UPADATE or INSERT, It refreshes the object.

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

This example assumes that the database trigger can keep the lastModified attribute as the current time.

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

The attribute should also be identified as read-only. the read-only attribute is implemented using the updatable and insertable annotations @ 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.

If both values are set to false, the attribute list will not appear in the INSERT or UPADATE statement. The values of these columns will be generated by the database.

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

GenerationTime. INSERT is used only when SQL INSERT is used to obtain the default value of the database.

Hibernate also maps the property as not insertable. hibernate will also map to properties that cannot be inserted.

The @ ColumnDefault Hibernate annotation sets the default value of the column when Hibernate exports and generates the SQL schema DDL.

@ ColumnDefault attribute annotation, which sets the default attribute of the list when hibernate exports and generates 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 is often used in automatic value generation, or is generated through a database, such as in the previous example or generated by an application. You can carefully view the annotations in the code list 5.4 below.

The lastModified property of the last example was of type java. util. Date, and a database trigger on SQL INSERT generated its value.

The lastModifiied attribute in the java. utia. Date type in the preceding example and the SQL INSERT trigger value in the database.

The JPA specification requires that you annotate temporal properties with @ Temporal to declare the accuracy of
SQL data type of the mapped column.

The JPA specification requires that the @ Temporal annotation be used to declare the ing SQL data type.

The Java temporal types are java. util. Date, java. util. Calendar, java. SQL. Date, java. SQL. Time, and java. SQL. Timestamp.

Java has the following types: 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 also provides the java. time package in JDK 8. (In fact, if the converter is used, the annotation is unnecessary. In the next section, you will see the 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.

The next code list shows a JPA compatibility example. A typical field is created when it is saved once and is not updated.

 

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

OK. The book content is written in this way. Let's look at our own needs and implementations.

When defining the entity of JPA, we need to set the database timestamp. In general, there is a field requirement to record the creation time and the Update time of a field record. How does one perform this in hibernate configuration?

See the following:

@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;  
The getters and setters methods are omitted.

At Creation Time

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);

Sleep for one second, update
entityManager.getTransaction().commit();entityManager.close();// now lets pull events from the database and list thementityManager = entityManagerFactory.createEntityManager();entityManager.getTransaction().begin();  try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}         List
 
   result1 = entityManager.createQuery( "from RsSignUpUser", RsSignUpUser.class ).getResultList();for ( RsSignUpUser event : result1 ) {event.setBZ("bb");}        entityManager.getTransaction().commit();        entityManager.close();
 

You can see the database value:


Time exists. Of course, it can also be added to the definition of the database. However, it is found that the table comment and field comment cannot be generated in the table structure automatically generated by hibernate.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.