(GO) Hibernate persistence class and primary key generation strategy

Source: Internet
Author: User

http://blog.csdn.net/yerenyuan_pku/article/details/65462930

Hibernate Persistence Class

What is a persistent class? The English name of the persistence class in Hibernate is Persistent Object (PO), PO=POJO+HBM mapping configuration file.
For the PO in Hibernate, the following rules are written:

    1. You must provide a non-parametric public construction method.
    2. All attributes are to be decorated with private, providing public get/set methods externally.
    3. The PO class must provide an identity attribute that corresponds to the primary key in the database, which we call the OID.
    4. The properties in the Po class use the wrapper class of the base data type as much as possible.
    5. The PO class cannot use the final modifier.

For the 1th and 2 points, do not need to say a lot, I would highlight the following 3 points.

Why does the PO class have to provide an IDENTITY property oid that corresponds to the primary key in the database?

An OID refers to a property that corresponds to the primary key of a table in the database. The hibernate framework distinguishes between different PO objects through OIDs, and Hibernate considers them to be the same object if there are two identical OID objects in memory. It's not very well understood, it involves the concept of hibernate caching, because hibernate is directly manipulating the database, so we definitely provide some caching strategies to optimize it. So how do we know this object is not duplicated in the cache? We are distinguished by the OID.

Why should the attributes in the PO class use the wrapper class of the base data type as much as possible?

There is no way to describe a concept that does not exist, and if you use a wrapper type, it is an object, the default value for an object is null, and we know that if it is null, it means that it does not exist, then it can help us to describe a concept that does not exist.

Why can't the PO class use the final modifier?

To answer this question, you have to know the difference between the Get/load methods in Hibernate. This is also the usual test in hibernate. I'll give you the answer first:

Although the Get/load methods are all based on the ID to query the object, but the difference between them is quite large:
1. The Get method directly gets a persisted type object, which is the immediate query operation, which is what I want to find out. The Load method It gets is the proxy type object (subclass object) of the persisted class. It uses a delay strategy to query the data. If the PO class uses the final modifier, it will error because the final decorated class cannot be inherited.
2. When the Get method is queried, if there is no return Null;load method at query time, an exception--org.hibernate.objectnotfoundexception will occur if it does not exist.

Now to the programming to understand the above paragraph, first of all we have to take a good hibernate development environment, read my article in front of the children's shoes, should be able to quickly build a good, do not do too much to repeat.
To create a new unit test class--hibernatetest.java under the Cn.itheima.test package, we first test the Get () method in Hibernate.

public class HibernateTest {    // 测试get/load方法的区别    @Test    public void test1() { Session session = HibernateUtils.openSession(); session.beginTransaction(); // 操作 Customer customer = session.get(Customer.class, 3); System.out.println(customer.getClass()); // cn.itheima.domain.Customer session.getTransaction().commit(); session.close(); }}

Test the Test1 () method to discover the Eclipse console printing:

Class Cn.itheima.domain.Customer

This indicates that the get () method directly gets a persisted type object.
If you change the Get method to the Load method, you can see that the Eclipse console prints:

Class Cn.itheima.domain.customer_$$_jvstd48_0

This seems to indicate that the Load method obtains the Proxy type object (that is, the subclass object) of the persisted class.
Now add a breakpoint to this line:

Customer customer = session.get(Customer.class, 3);

Then run the Test1 () method in breakpoint mode to find out that the Get method is immediately queried, and that is what I want to find out.
By changing the Get method to the Load method and running the Test1 () method in breakpoint mode, you can see that only a SELECT statement is sent to the database when we access the object's Get method . This already means that it uses a deferred strategy to query the data.
The T_customer table in the database is obviously not id=100 customer, and we are to query this customer, can try the Get/load () method respectively. The Get () method in Hibernate is also tested first.

public class HibernateTest {    // 测试get/load方法的区别    @Test    public void test1() { Session session = HibernateUtils.openSession(); session.beginTransaction(); // 操作 Customer customer = session.get(Customer.class, 100); System.out.println(customer); session.getTransaction().commit(); session.close(); }}

Test the Test1 () method to discover the Eclipse console printing null , which indicates that the GET method is returned if it does not exist at query time null .
Then the Get method is changed to the load method, you can find the following exception:

This already shows that the load method will produce an exception if it does not exist at query time org.hibernate.ObjectNotFoundException .

Hibernate primary key Generation policy

When defining hbm.xml mapping files and Pojo classes, you need to define a primary key, and the primary key types defined in Hibernate include the natural primary key and the proxy primary key:

    • Natural primary KEY (business primary key)
      A field with business meaning as the primary key, such as: School number, Social security number.
    • Proxy primary key (logical primary key)
      A field that does not have a business meaning as a primary key (for example, a self-increment ID), such as the MySQL self-increment primary key, the unique sequence string generated by the primary key, UUID () method generated by the Oracle sequence.

Recommendation: Use the proxy primary key in enterprise development!

primary Key Generator Description
Increment The proxy primary key. A variable is maintained by hibernate and automatically incremented each time a primary key is generated. Issue: If there are multiple apps accessing a database, the primary key may conflict at this point because each app maintains its own primary key. recommendations are not adopted . Advantages: It is easy to cross database platform. Cons: not suitable for high concurrent access.
Identity The proxy primary key. Generated by the underlying database identifier. The condition is that the database supports auto-grow data types. For example: MySQL's self-increment primary key, Oracle does not support automatic generation of primary keys. if the database supports self-increment recommendation adoption . Pros: Maintained by the underlying database, regardless of hibernate. Cons: Valid only for databases that support autogrow, such as MySQL.
Sequence The proxy primary key. Hibernate generates identifiers based on the underlying database sequence. The condition is that the database supports sequences, such as the sequence of Oracle. If the database support sequence is recommended for use. Pros: Maintained by the underlying database, regardless of hibernate. Disadvantage: The database must support sequence scenarios, such as Oracle.
Native The proxy primary key. Automatic selection of identity, sequence, Hilo based on the underlying database is not recommended because control of the generated primary key policy is controlled by Hibernate . Advantage: Used when there are multiple databases in the project. Cons: Low efficiency.
Uuid The proxy primary key. Hibernate uses a 128-bit UUID algorithm to generate identifiers. The algorithm can generate a unique string identifier in a network environment. This policy guarantees the uniqueness of the primary key generation, and provides the best database insert performance and database platform independence. recommended for use . Advantages: Database-Independent, convenient database porting, high efficiency, do not access the database can directly generate primary key value, and it can guarantee uniqueness. Disadvantage: The UUID length is large (32 hexadecimal digits), occupying a larger space, corresponding to the Char/varchar type in the database.
Assigned Natural primary key. The Java program is responsible for generating identifiers. not recommended for use . Try to avoid manual operation of the primary key in the operation.

After understanding the above knowledge, I will tell you how to configure.

  • Increment

     <id name= "id" column=" id "type=  "int" > <!--Java Data Type--<generator  Class= "increment" ></generator ></ID>                    
  • Identity

    <id name="id" column="id" type="int"> <!-- java数据类型 --> <!-- 主键生成策略 --> <generator class="identity"></generator></id>
  • Sequence

    <id name="id" column="id" type="int"> <!-- java数据类型 --> <!-- 主键生成策略 --> <generator class="sequence"></generator></id>

    If this is configured, the default sequence used is hibernate_id. But you can also assign a sequence to it, such as manually creating a sequence in the Oracle database, creating a sequence syntax in the Oracle database: create sequence sequence name;  , then this is the configuration:

    <id name=  "id" column= "id" type=" int "> <!--Java Data Type--<!--primary key generation strategy--<generator class= "sequence" > < param name= "sequence" > Sequence name Span class= "Hljs-tag" ></param> </ generator></ID>   
      • 6
  • Native

     <id name= "id" column=" id "type=  "int" > <!--Java Data Type--<generator  Class= "native" ></generator>< Span class= "Hljs-tag" ></ID>                    
  • UUID

     <id name= "id" column=" id "type=  "string" > <!--Java data Type-- <!--primary key generation strategy--<generator Span class= "Hljs-attribute" >class= "uuid" ></generator></ID>     

    Note: The type of the primary key should be string.

  • Assigned

    <id name="id" column="id" type="int"> <!-- java数据类型 --> <!-- 主键生成策略 --> <generator class="assigned"></generator></id>

    Note: Try to avoid manual primary key operation in the operation.

Three states of persisted objects

There are three types of persisted objects in hibernate:

    1. Transient state: Also known as temporal State or Free State, it refers to our new object, which does not exist OID, is not associated with Hibernate session, and is not recorded in the database. When it is finished, it is recycled directly by the JVM, and it is used for information portability only.
      Simply stated: There is no OID and is not associated with the information in the database, not within the session management scope.
    2. Persistent state: Within the Hibernate session management scope, it has a persistent identity oid. It is characterized by persistent state until the transaction has been committed, and hibernate is detectable when it has changed.
      Simply put: There is OID and is managed by the session, it is possible in the database, there may be no.
    3. Off-state: Also known as Free State or off-line state, it means that the persistent state object loses its association with the session, and the off-state object has an OID, which may exist in the database, or it may not exist. For a Hibernet object, it cannot be detected when it has changed.

Next, test the three states of the persisted object in the following code:

public class hibernatetest {//test three states of persisted objects @Test public void test2 () {//1. Get Session Session session = Hibernateutils.opensession (); Session.begintransaction (); Customer c = new customer (); //transient state (no OID, not associated with session) C.setname ( "Zhang San"); C.setsex ( "male"); Session.save (c); //establish the relationship between C and session, it is persistent (with OID) //2. Transaction commit and Close session Session.gettransaction (). commit (); Session.close (); System. out.println (C.getid ()); //disconnected from the session, it is off-state (with OID)}}         
Persistence class switching between three states

The basis for judging the three states of a persisted class object:

    1. Whether there is an OID
    2. Determine if the session is associated

The switch between three states of a persisted class object can be consulted:

I'll give you a little explanation:

  1. Transient state (new out)
    Instantaneous → persistent: save (), Saveorupdate () method
    Instantaneous → off-tube (free): The OID can be set manually, but this is not recommended. As follows:

    public class HibernateTest {    // 测试持久化对象的三种状态    @Test    public void test2() { // 1.得到session Session session = HibernateUtils.openSession(); session.beginTransaction(); Customer c = new Customer(); // 瞬时态(无OID,与session无关联) c.setName("张三"); c.setSex("男"); c.setId(7); // 瞬时→脱管(游离) System.out.println(c.getId()); }}
  2. Persistent state, which is managed by the session.
    Persistent → Instantaneous: delete ()--after this operation is equivalent to the database inside there is no such record, the deleted persistent object is not recommended to use.
    Persistent → off-tube: Note that the session itself is cached, and its cache is what it says is the first level of caching.

    • Evict: Clears an object specified in the first level cache
    • Clear: Clear the first-level cache
    • Close: Closes, or clears the cache level
  3. Off-State (we need to know that it is not directly available)
    Off-tube → Instantaneous: the OID is removed directly (this is not recommended, as we do not recommend manipulating the off-state object). Such as:

    public Span class= "Hljs-keyword" >class hibernatetest {//test three states of persisted objects @Test public void test2 () {// 1. Get session Session session = Hibernateutils.opensession (); Session.begintransaction (); Customer c = new customer (); //transient state (no OID, not associated with session) C.setname ( "Zhang San"); C.setsex ( "male"); C.setid (7); //instantaneous → de-tube (free) c.setid (null); //off the Tube (free) → instantaneous System. out.println (C.getid ());}          

    Off-tube → persistent: update, saveorupdate, lock (OBSOLETE) is not recommended.

(GO) Hibernate persistence class and primary key generation strategy

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.