Hibernate framework--object's state, cache, map

Source: Internet
Author: User

Review Hibernate the next day:

1. One-to-many and Multi-pair

2. Many-to-many

3. Inverse/cascade

4. Maintenance of related relationships

Pair of More:

<set name= "mapped Collection properties" table= "(optional) the corresponding foreign key table for collection properties" >

<key column=, foreign key field for foreign key table/>

<one-to-many class= "type of collection element"/>

</set>

Many-to-one:

<many-to-one name= "object properties" class= "object type" column= "foreign key field field"/>

Many-to-many

<set name= "" table= "" >

<key column= ""/>

<many-to-many column= "" class= "" >

</set>

Goal:

Part 1th: the state of the Object:

Part 2nd: Caching

1) Cache Level

2) Related knowledge

----lazy loading---

Part 3rd: Mapping

One-to-one mapping

Component Mappings

Inheritance Mappings

I. The state of an object

Example: User user = new user ();

The state of an object in Hibernate: temporary/transient state, persistent state, free State.

1. Temporary status

  Characteristics:

A direct new object;

Not in the management of the session;

There are no records of objects in the database;

1. Persistence status

  The object is persisted when the Session's save/saveorupdate/get/load/list is Called.

Objects that are in a persisted state are reflected in the database when changes are made to the object properties!

  Characteristics:

  In the management of the session;

There are corresponding records in the database;

3. Free State

  Characteristics:

Not in the management of the session;

There are corresponding records in the database

The state of the object after the session is closed;

Transformation of Object state

 public classUser {Private intuserId; PrivateString userName;  public intgetUserId () {returnuserId; }     public voidSetuserid (intUserId) {         this. UserId =userId; }     publicString getusername () {returnuserName; }     public voidsetusername (String UserName) { this. UserName =userName; } @Override publicString toString () {return "User [userid="+ UserId +", Username="+ UserName +"]"; }        }

<hibernate-mapping package= "cn.itcast.a_status">        <classname= "User"Table= "t_user">        <IDname= "userId"column= "id">            <Generatorclass= "native"></Generator>        </ID>            < propertyname= "userName"></ property>    </class>    </hibernate-mapping>
 public classApp1_status {Private Staticsessionfactory sf; Static{SF=NewConfiguration (). Configure (). addclass (User.class)//Use when testing. Buildsessionfactory (); }    //1. Conversion of object state@Test public voidtestsaveset () throws Exception {session session=sf.opensession ();                Session.begintransaction (); //Create object "temporary state"//User user = new user ();//User.setusername ("Jack22222"); //Save Persistent State//Session.save (user); //User.setusername ("Jack333333"); //is reflected in the database//EnquiryUser user = (user) Session.Get(User.class,5); User.setusername ("Tomcat");//hibernate automatically matches the database (first-level cache) and updates the database if it is the samesession.gettransaction (). Commit ();                        Session.close (); User.setusername ("Jack444444444"); //Print "free state"System. out. println (user.getuserid ()); System. out. println (user.getusername ()); } @Test public voidBak () throws Exception {session session=sf.opensession ();        Session.begintransaction ();        Session.gettransaction (). Commit ();    Session.close (); }}

二、一级 Cache

Why use caching?

Purpose: reduce the number of accesses to the database! To improve hibernate execution efficiency!

Hibernate Cache Classification:

Cache Level

Second-level Cache

ü Concept

1 ) Hibenate Medium-level cache, also called session cache, which can be used in the session  reduce the number of database accesses in the range! only valid in session range! Session closed, first-level Cache failed!

2 ) When the session is called the Save/saveorupdate/get/load/list/iterator method, The object is placed in the session in the Cache.

3 )Session cache is maintained by Hibernate , the user cannot manipulate the cached content , and if you want to manipulate the cache content, you must pass the evit/provided by hibernate Clear Method Operation.

Characteristics:

only in the ( current) session Range is valid, the action time is short, the effect is not particularly obvious!

in a short period of time to operate the database, the effect is more obvious!

ü The role of several methods of cache correlation

Session.flush (); Synchronizing a first-level cache with a database

Session.evict (arg0); Empties the specified object in the First-level cache

Session.clear (); Empties all cached objects in the First-level cache

In what situation is the above method used?

Use for bulk operations:

Session.flush (); Synchronize with Database First

Session.clear (); Then empty the First-level cache content

U face question 1: will different sessions share the cached data? Not.

User1 u1 = Session1.get (user.class,1); put the U1 object into the Session1 cache

Session2.     Update (u1); Put the U1 into the Session2 cache.

U1.setname (' New Name ');

If you generate 2 update sql, it means that different sessions use different buffers and cannot be shared.

U face question 2:list and iterator query difference?

List ()

Check out all the records at once,

will be placed in the cache, but will not fetch data from the cache

Iterator

N+1 query; n Indicates the total number of records

A statement is sent to query the primary key (1) for all RECORDS.

Then go to the database query based on each primary key (N)!

will be put into the cache, and the data will be taken from the cache!

 public classApp2_cache {Private Staticsessionfactory sf; Static{SF=NewConfiguration (). Configure (). addclass (User.class)//Use when testing. Buildsessionfactory (); } @Test public voidTestcache () throws Exception {session session=sf.opensession ();        Session.begintransaction (); User User=NULL; //Enquiryuser = (user) Session.Get(User.class,5);//first check the cache for data, if you do not query the database, directly from the cacheuser = (user) Session.Get(User.class,5);//this sentence will no longer send a query command to the database, reducing the interaction with the Database. session.gettransaction (). Commit ();    Session.close (); } @Test public voidflush () throws Exception {session session=sf.opensession ();                Session.begintransaction (); User User=NULL; User= (User) Session.Get(User.class,5); User.setusername ("Jack"); //cached data is synchronized with the databaseSession.flush (); User.setusername ("jack_new");  Session.gettransaction (). Commit (); //Session.flush ();Session.close (); } @Test public voidClear () throws Exception {session session=sf.opensession ();                Session.begintransaction (); User User=NULL; //Enquiryuser = (user) Session.Get(User.class,5); //Empty Cached content//session.clear ();//Clear AllSession.evict (user);//clears the specifiedUser= (User) Session.Get(User.class,5);  Session.gettransaction (). Commit (); //Session.flush ();Session.close (); } @Test public voidsessiontest () throws Exception {Session Session1=sf.opensession ();        Session1.begintransaction (); Session Session2=sf.opensession ();                Session2.begintransaction (); //user into the session1 bufferUser user = (user) session1.Get(User.class,1); //user into the session2 buffersession2.update (user); //Modifying ObjectsUser.setusername ("New Name");//2 Updatesession1.gettransaction (). Commit (); //Session1.flush ();Session1.close ();  Session2.gettransaction (). Commit (); //Session2.flush ();Session2.close (); }}

Hibernate framework--object's state, cache, map

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.