Hibernate leak Check 2

Source: Internet
Author: User
Tags bulk insert

Hibernate object state

Instantaneous (transient): Created by the new operator and not yet associated with the hibernate session. Instantaneous objects are not persisted to the database and are not given persistent identities.

Persistent (persistent): persisted instances have corresponding records in the database and have a persistent identity.

The persisted instance may have just been saved, or just loaded, whatever it is, it only exists within the associated session scope. This is important. Hibernate detects any changes to objects that are in the persisted state, and synchronizes the object data with the database when the current operating unit finishes execution.

Off-tube (detached): When the session associated with the persistence object is closed, the object becomes a de-tube state.

Hibernate's first level cache (session cache)

When the session is called Save (), update (), Saveorupdate (), load () or get () method, and the list (), iterator () or filter () method that invokes the query interface, If there are no corresponding objects in the cache, Hibernate adds the object to the session cache.

Like what:

 Transaction Transaction = Session.begintransaction (); Feeling feeling  = (feeling) session.get (Feeling.        Class , 1);        System.out.println (feeling);        System.out.println (Feeling.getfeelingcomments ()); Feeling feeling1  = (feeling) session.get (Feeling.        Class , 1); Transaction.commit ();  
Hibernate:     Select        feeling0_.feeling_id  as feeling1_1_0_,        feeling0_.content as content1_0_,        Feeling0_.id as id1_0_     from        feeling feeling0_     where        feeling0_.feeling_id =?[ Email protected]hibernate:     Select        feelingcom0_.feeling_id as feeling3_1_1_,        feelingcom0_. feelingcomment_id as  feelingc1_1_,        feelingcom0_.feelingcomment_id as  feelingc1_2_0_,        Feelingcom0_.content as content2_0_,        feelingcom0_.feeling_id as feeling3_2_0_,        feelingcom0_.id as id2_0_     from        feeling_comment feelingcom0_     where        feelingcom0_.feeling_id=?[ [Email protected], [email protected], [email protected], [email protected]

You can see that the second get () does not generate SQL.

You can use 1.evict () to purge the specified persisted object from the cache. 2.clear () Clear all .... In most cases, the above two methods are not advocated for managing caching.

When the properties of an object in the session cache change, the session does not immediately clean up the cache and executes the associated SQL to synchronize the database, only to clean up the cache at the point in time of the feature. This allows the session to combine several related SQL into one to improve performance.

The points of time for the above features include:

1. Call the Commit () method of transaction. This clears the cache and then commits the transaction to the database. This is done to minimize access to the database and, as much as possible, to shorten the time that the current transaction locks on related resources in the database.

2. Perform some query operations. This is done to ensure that the results returned by the query are immediate and correct.

3. Explicitly call flush (). Note that flush () does not commit the transaction, and the data may be rollback.

The most common usage for flush () is, of course, bulk operation. For example, BULK insert 100,000 data.

 for (int i=1;i<100000;i++) {    customer c=new  customer ();    Session.save (c);     if (i%20==0) {         session.flush ();         Session.clear ();    }}

Set the hibernate.jdbc.batch_size=20. A certain number (20) is forced to be brushed out, synchronizing the cache with the database (data is written to the database), and then emptying all caches to avoid memory overflow.

load () and get ()

Http://www.cnblogs.com/binjoo/articles/1621254.html

Note the flow of the two: The Get method first query the session cache, no query level two cache, and finally query the database; Instead, the Load method first queries the session cache, does not create proxies, and queries level two caches and databases when the data is actually used.

For load (), if it is just feeling feeling = (feeling) session.load (Feeling.class, 1); is not issued SQL, only like System.out.println (feeling); This will only be emitted if the feeling is used.

Load () is just the dynamic proxy that generates the class, and does not load the database's data into the appropriate class, so it is suitable for use when data is updated or when foreign key data is inserted for a table.

As in the example of the friend classification in Hibernate leak 1, insert the new friend and add him to the existing category.

Friend_category FC =Newfriend_category (); Fc.setcategory_name ("Existing friends category"); USER_FRIEND_PK PK=NewUSER_FRIEND_PK ();        Pk.setfriend_name ("new Friend"); Pk.setname ("Theviper"); User_friend uf=NewUser_friend ();        UF.SETUSER_FRIEND_PK (PK); Friend_category FC1=(friend_category) session.load (friend_category.class, 1);        Uf.setfriend_categorys (FC1); //Uf.setsort ("good base Friend");session.saveorupdate (FC1); Session.save (UF);

Note that at this point the load is friend_category with saveorupdate (), otherwise an exception will occur org.hibernate.PersistentObjectException:uninitialized Proxy Passed to save ().

Many people are using the Spring hibernatetemplate template. It has a bad place, such as:

        Feeling f = hibernatetemplate.load (feeling.  Class, 1);        System.out.println (f);

Return exception Org.hibernate.LazyInitializationException:could not initialize Proxy-no Session

The reason is that hibernatetemplate and spring's other DAO templates, like JdbcTemplate, go the following process:

1. Prepare resources->2. Start->3. Data access->4. Returns data->5. COMMIT/ROLLBACK TRANSACTION->6. Handling Exceptions Closing Resources

The 3,4 are written by us, and the others are made for us by templates. In other words, each time the Hibernatetemplate method is used, Hibernatetemplate will shut down the resources, prevent the database connection, memory leaks, The closed resource includes Hibernate's session.session, which naturally does not find the Session cache and the class's dynamic proxy (load () returned).

Cascade

Used in <set>,<one-to-one>,<many-to-one> (individuals feel useless in many-to-one).

Hibernate log

Hibernate Second Level cache

A process or cluster-wide cache, the sessionfactory level, and the first-level cache is a transaction-scoped cache. The second-level cache holds the bulk of the object's data.

The second level caches 4 concurrent access policies, each of which corresponds to a level of transaction isolation.

    • Transactional type (transactional): adapts only in managed environments. Provides the REPEATABLE read transaction isolation level for data that is frequently accessed but rarely modified to prevent concurrency problems such as dirty reads and non-repeatable reads.
    • Read-write (Read-write): Read COMMITTED transaction isolation level, only applicable in non-clustered environments. Suitable for frequently accessed but rarely modified data to prevent dirty reads.
    • Non-strict read-write (Nonstrict-read-write): does not guarantee the consistency of the cache with the data in the database. If two transactions access the same data in the cache, you must have a very short data expiration time for that data to avoid dirty reads. This is true for data that is rarely modified and allows for occasional dirty reads.
    • Read-only (Read-only): Applies to data that is never modified.

The transactional has the highest isolation level and the lowest concurrency performance; read-only is the reverse.

Cache plug-ins can be divided into process-scoped caches (Ehcache,oscache) and cluster-scoped caches (Swarmcache,jbosscache). The query cache is not supported in Swarmcache.

Configure Hibernate.cfg.xml

        <name= "Hibernate.cache.use_second_level_cache">true</ Property >        <name= " Hibernate.cache.provider_class ">org.hibernate.cache.EhCacheProvider</  Property>

Hibernate allows you to configure level two caching on classes and collections, with <cache> child elements on <class> and <set>.

Usage: <cache usage= "transactional|read-write|nonstrict-read-write|read-only" region= "RegionName" include= "all| Non-lazy "/>

Usage: Specifies the concurrency access policy. Region: Specifies the zone name of the level two cache, which defaults to the name of the class or collection. Include: Specifies that when an object is cached, its mappings to deferred-loaded properties will not be cached. Default all.

Ehcache Configuration

When configuring <cache>, it is important to note that <cache> under <set> is also required to be configured at <class> on the other side of <set> to be effective.

Manage Level Two cache

Sessionfactory.evict (Category.class,new Long (1));//Clears Category object with ID 1 in level two cache

Sessionfactory.evict ("Mypack. Category ");//Clear all objects of category class in level two cache

Sessionfactory.evictcollection ("Mypack. Category.items ");//clear the Items collection for all objects of category class in level two cache

Session vs. Level Two cache interaction mode:

Represented by the 5 static constants of the Org.hibernate.CacheMode.

    • Cachemode.normal: Normal mode (default), session reads and writes data to the level two cache.
    • Cachemode.ignore: Ignore mode, session does not read to level two cache and does not write data.
    • CacheMode.GET:Session the level two cache is read-only and does not write.
    • CacheMode.PUT:Session write to level two cache is not correct.
    • Cachemode.refresh: Refresh mode, session does not read data from the level two cache, but it writes data read from the database. The difference between the and put is that refresh ignores the Hibernate.cache.use_minimal_puts property in the configuration file and forces all data in the level two cache to be refreshed.

Usage: Session.setcachemode (cachemode.ignore);

Hibernate leak Check 2

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.