About lazy loading (lazy) and forced loading (hibernate.initialize (Object proxy))

Source: Internet
Author: User

PO is persistence Object

VO is the value Object

PO and Vo are two of the most critical concepts of the number encyclopedia in hibernate.

First, what is Vo, very brief, VO is a brief value policy.

Such as:

TUser user = new TUser ();

User.setname ("Emma");

The user here is a VO. VO just abbreviated Keyword Mining tool carries some characteristic information of the policy.

What is PO? This is the VO that is classified into hibernate processing structure. Look at the following two examples:

?

TUser user = new TUser ();

TUser anotheruser = new TUser ();

User.setname ("Emma");

Anotheruser.setname ("Kevin");

Now both user and Anotheruser are VO

Transaction tx = Session.begintransaction ();

Session.save (user);

Now the user has gone through Hibernate's disposition to become a PO, and Anotheruser is still a VO

Tx.commit ();

After the business is submitted, a user "Emma" is now documented in the library table and nothing is done about Anotheruser.

Transaction tx = Session.begintransaction ();

User.setname ("emma_1"); PO

Anotheruser.setname ("kevin_1");//vo

Tx.commit ();

After the business is submitted, PO's condition is solidified into the database, that is, the database "Emma" user records have now been updated to "emma_1", at the moment Anotheruser is still a common Java policy, its characteristics change will not have any impact on the database, other, The policy of returning from Hibernate is also PO: A PO returned by hibernate, such as:

TUser user = (TUser) session.load (tuser.class,new Integer (1));

Vo is processed by hibernate and becomes a PO. In the example code above session.save (user), we keep a Vo "user" passed to hibernate by the Session.save method. In the Save method, Hibernate enters the

The following disposition is done:

1. In the entity Map that corresponds to the session at that time, the query is not a citation of the user policy.

2. If the citation exists, return directly to the user policy Id,save process is complete. Hibernate, there is an entity container for each session (in practice, a map policy), and if the guidelines are already documented in this container, hibernate will now be associated with the session.

With respect to the save operation, if the policy is now relevant to the session (that is, it is now in the entity container of the session), no detailed action is required. As a result of the subsequent Session.flush process, Hibernate will traverse the policy in this entity container, find the entity that is being changed, and generate and fulfill the corresponding update sentence.

3. If the citation does not exist, the insert operation is performed according to the mapping contact.

A) In our example, native's ID generation mechanism is used, so hibernate takes the ID generated by the insert operation from the database and assigns the ID feature of the user policy.

b) Attribution of user policy citation to Hibernate's entity container.

c) The save process is complete and the policy ID is returned.

In the session.load approach, Hibernate has now put this policy into its entity container before returning to the policy.

The first differences between VO and PO are:

. Vo is a standalone Java Object.

. The PO is a guideline that is subsumed into its entity container (ENTITYMAP) by Hibernate, which represents the number of

According to the corresponding Hibernate entity in the library, the change of PO will be reflected in the business submission to the actual

In the international database. If a PO has a separation from the entity container corresponding to the session (such as the PO after the session is closed), then

At the moment, it will become a VO again.

About Unsaved-value

In the case of non-apparent data retention, Hibernate will use this value to determine whether the policy is required to be retained.

The so-called explicit reservation, refers to the code in the clear call session of Save, update, Saveorupdate method to persist the policy. Such as:

Session.save (user);

In some cases, such as mapping contacts, Hibernate preserves the join class based on cascading (Cascade) connections. There is no presentation of the cascading policy in the code at this time, the requirement hibernate is based on the policy

is not required to be persisted to the database. At this moment, Hibernate is determined on the basis of Unsaved-value.

First hibernate will take out the policy ID. Later, this value is compared with unsaved-value, if equal, the policy policy is not retained, otherwise, the policy is now reserved, no need to carry out the retention operation.

such as: User policy is previously obtained from Hibernate from the database, together, this user policy of a number of relevant policy address is also loaded, now we add an address policy to the user policy, now call

Session.save (user), Hibernate will determine the number of address of user policy based on Unsaved-value

In the policy, which requirements fulfill the save operation, and which do not need.

As far as our new address policy is concerned, because its ID (integer) is not assigned and therefore NULL, it is the same as the Unsaved-value (null) we set, so hibernate treats it as an unreserved policy and will generate an insert for it Sentences and fulfill them.

Here can be a question, if the "original" about the policy changes (such as the user's "original" address policy characteristics of the attack change, so-called "original" that this address policy is now related to the user, rather than we add in this process), now ID Values are read from the database, and no seizures change, natural

Unlike unsaved-value (null), is hibernate not retained?

In the above comments on Po, VO in the past related to the question of data retention, in practice, the "reservation" here, in practice is "insert" concept, only about the new policy of participation, rather than the database Huaxia has the relevant policy

"Update". The so-called new policy, usually can be understood as not related to the session of the VO. The "original" relevant policy is PO. :

With respect to the save operation, if the policy is now relevant to the session (that is, it is now in the entity container of the session), no detailed action is required. Due to the subsequent Session.flush process, Hibernate

The guidelines in this entity container are traversed to find the entities that are being changed, and the corresponding update sentences are generated and fulfilled.

Inverse and Cascade

Inverse, the literal translation of "rotation." In hibernate semantics, inverse specifies the direction in which the phase is connected. In the phase relation, the inverse= "false" is the active side, which is connected by the active side as the protection phase. See descriptions in one-to-many links in detail.

and Cascade, translated as "Cascade", indicating the principle of cascading links, such as Tuser's cascade set to all, it is indicated that if the attack on the user policy operation, the requirements of the user's policy is also carried out the same operation. If you perform a save operation on the user policy, it is necessary to perform the save operation on the address of the user policy.

Beginners often mix inverse and cascade, in practice, this is two unrelated concepts. Inverse refers to the control direction of the phase connection, and Cascade refers to the chain operation between the levels.

Deferred load (Lazy Loading)

In order to prevent some cases, the relationship between the unnecessary costs of utility. Hibernate introduces the concept of deferred loading. For example, when the user policy is loaded, it will read multiple address policies

The active loading mechanism for data is really useful in terms of the application logic that requires the address to be manipulated. However, if we just want to get the user's gender (sex) trait, and don't care about the user's address

Information, the feature of active load address appears to be surplus, and it creates a great utility waste. In order to get the gender characteristics of the user, we can also read a number of useless address data from the database, which leads to a lot of unnecessary system expenditure.

Delay loading the rendering of the feature just to handle this question. The so-called deferred loading, that is, in the demand data at the time of the real performance of data loading operations.

The process of loading the user policy here means that the user policy is loaded only for its own characteristics, and when we need to obtain the address information about the user policy (e.g. when performing user.getaddresses), only

Real loads the address data from the database and comes back.

The quiz fulfills the following code:

Criteria = Session.createcriteria (Tuser.class);

Criteria.add (Expression.eq ("name", "Erica"));

List userlist = Criteria.list ();

-Indexread arguments from command-line "http://www.shoudashou.com"

-Indexread arguments from command-line "http://www.4lunwen.cn"

-Indexread arguments from command-line "http://www.zx1234.cn"

-Indexread arguments from command-line "http://www.penbar.cn"

-Indexread arguments from command-line "http://www.whathappy.cn"

-Indexread arguments from command-line "Http://www.lunjin.net"

-Indexread arguments from command-line "http://www.ssstyle.cn"

-Indexread arguments from command-line "http://www.91fish.cn"

-Indexread arguments from command-line "http://www.fanselang.com"

TUser user = (TUser) userlist.get (0);

System.out.println ("User name =" +user.getname ());

Set Hset = user.getaddresses ();

Session.close ();//Closed session

Taddress addr = (taddress) hset.toarray () [0];

System.out.println (Addr.getaddress ());

The runtime throws an anomaly:

Lazyinitializationexception-failed to lazily initialize a collection-no session or session was closed

If we make a slight adjustment and put session.close at the end of the code, we will not have such a problem. This means that as long as we practice loading user-related address, Hibernate attempts to pass

The session loads the practice data set from the database, and since we have closed the session before we read the address, we report that the session has been closed.

Here is a question, if we use the deferred loading mechanism, but expect in some cases to complete the function of non-deferred loading, that is to say, we expect the session closed, still agree to operate the user's addresses

Characteristics. For example, in order to supply data to the view layer, we need to provide a good user policy, including the address information, and this user policy is necessary to be able to use after the session closed.

Hibernate.initialize method can be forced to load the relevant policy to accomplish this function:

Hibernate.initialize (User.getaddresses ());

Session.close ();

Forced reading of data by Hibernate.initialize method

Addresses policy can be operated from session

Set hset= user.getaddresses ();

Taddress addr = (taddress) hset.toarray () [0];

System.out.println (Addr.getaddress ());

Hibernate has made a lot of efforts to complete the transparent deferred loading mechanism. This includes the standalone completion of the JDK collection interface.

If we test the set-type policy of using HashSet to forcibly convert hibernate back:

Set Hset = (HashSet) user.getaddresses ();

is going to get a java.lang.ClassCastException in the run-time, in practice, it comes back to a specific Set of hibernate to complete the "net.sf.hibernate.collection.Set" approach, rather than

The JDK set in the traditional sense is complete. This is precisely why we are writing Pojo, it is necessary to use the Jdkcollection interface (such as Set,map), rather than a specific jdkcollection completion class (such as HashSet, HASHMAP) to declare the collection characteristics of the reasons.

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.