[Hibernate] Some Usage skills of Hibernate

Source: Internet
Author: User

Http://blog.csdn.net/chjttony/article/details/6042138

1. hibernate is now the most popular open-source object relational ing (ORM) Persistence framework. The SSH framework combination is the first choice for many Java EE projects. The designer of Java persistence framework (JPA) is the author of hibernate, therefore, some basic knowledge of Hibernate is summarized in the JPA learning notes. This article only summarizes some tips for using hibernate.

2. The State in object 3:

The lifecycle of an object is a key concept in hibernate. There are three states in the lifecycle of an object:

(1). Transient (Free State): An object exists freely in the memory and has nothing to do with the records in the database.

(2 ). persisent (persistent State): Also called managed State, that is, the object is under the State managed by the Hibernate Persistence framework. In this state, reference of the object is managed by the hibernate object container, if the object is in this State, its changes will be persistently stored in the database by hibernate.

(3). datached (Free State): the object in the persistent state. After the session instance is closed, the object is in the Free State. Objects in the Free State can be changed to persistent state again through update.

Note: The difference between the Free State and the free state is that the free state does not have a record of this object in the database, and the Free State object has a corresponding record in the database, it is only out of the management of the Hibernate Persistence framework, and its status changes cannot be updated to the corresponding records in the database table.

3. Value Object (VO), Persistent Object (PO), and data transmission object (DTO ):

(1). Value Object (VO): an object that represents a value. It is a relatively independent object and is in an unmanaged state.

(2 ). persistence object (PO): the object managed by the persistence framework, representing the entity corresponding to a record in the database. Its changes will be updated to the actual database when the transaction is committed.

(3 ). data transmission object (DTO): When the persistence interacts with the business logic layer or the view layer, the persistence object (PO) is first constructed into a value object (VO) through construction ), then, when this value object (VO) is passed to the required layer, the value object acting as the data transmission media (VO) is now called the data transmission object (DTO ).

4. Differences between get and load in hibernate:

There are two methods to get objects in hibernate: Get method and load method. However, there are some differences between the two methods. Beginners may not be familiar with them, and errors may occur if they are improperly used, their differences are as follows:

(1 ). the get method first searches through the internal cache. If no data is found, the get method directly retrieves data from the database. If no corresponding value exists in the database, the get method returns NULL.

(2 ). if the load method fails to find data from the internal cache, instead of directly retrieving data from the database, it also queries the second-level cache, and may return the object proxy. If no value exists in the database, the load method throws an exception in objectnotfoundexception.

5. Differences between the SAVE and persist methods in hibernate:

In hibernate, there are two methods for Object Persistence: Save and persist. These two methods are used to save the Free State object to the database and change it to a managed State object, however, the two methods have the following differences:

(1) If no transaction exists, the persist method is not executed.

(2) If no transaction exists, the SAVE method inserts records in the database and rolls back the database.

6. Hibernate query method:

Hibernate supports two query methods: Hibernate query language (hql) and criteria query.

(1 ). hql: it is an Object-Oriented Query Language provided by hibernate. It is mainly completed through the query interface. It is similar to the SQL statement, but does not operate on tables or columns in tables in hql, the operation is performed on the attributes of the object and the object. For example, the hql statement for querying the person object with a given name is query. createquery ("select P from person P where p. name =: Name "). setparameter ("name", name );
(2). Criteria: a more Object-Oriented Query Method than hql. It is called a completely object-oriented query method, which is quite different from the SQL statement. Like the example in (1), criteria is written as follows:

Criteria = session. createcriteria (person. Class); // Add the query condition criteria. Add (restrictions. eq ("name", name ));

For hql and criteria, you can choose to use hql and criteria. during runtime, Hibernate converts them into local SQL statements.

7. hibernate delayed loading problem:

When querying an object, if the object also references other objects, all the objects referenced by the object will also be queried during the query, in this way, the performance will be very poor when querying large volumes of data. To solve this problem, Hibernate uses lazy to query only the objects to be queried by default, the object referenced by this object can only be queried from the database when it is actually used, so that it can be queried on demand, greatly improving performance. However, delayed loading may also lead to other problems. For example, when an object is queried on a page and the referenced object of this object needs to be used elsewhere, an exception occurs when the object cannot be searched for because of the loss of the closed object of the hibernate session (Session. Common solutions to delayed loading:

(1) Someone provides a filter for opensessioninview, and openentitymanagerinview for JPA. This filter is used to save and open the hibernate session and JPA entitymanager when the page is opened, in this way, there will be no exception when the object value needs to be referenced and then searched from the database.

(2) identify an object and use hibernate. initialize (object) to initialize the object. In this way, the delayed loading mechanism will no longer work.

8. threadlocal:

Threadlocal is a class provided by Java JDK called a local variable in the thread. This class is used to store a copy of shared data in each thread to avoid mutual influence between threads. Its simple usage is as follows:

Threadlocal session = new threadlocal (); public static getthreadlocal () {// use the current thread as the key to obtain the value of the thread's local variable session S = (Session) session. get (); If (S = NULL) {S = This. getsession (); Session. set (s );}}

Threadlocal is equivalent to a map. Its key is the current thread and is valid only within one thread.

In hibernate, we use threadlocal to manage sessions. Multiple operations can share one session. This avoids repeated accesses to the same session.

9. hibernate batch operation:

In hibernate, sessions are thread-safe, while sessionfactory is thread-safe.

When hibernate executes the flush refresh method, the data in the first-level cache is synchronized with the database.

When operating a large volume of data in hibernate, memory overflow may occur. solution:

(1) Clear the data in the session, for example:

For (INT I = 0; I <1000000; I ++) {session. save (OBJ); // refresh the session cache once for every 100 records. If (I % 100 = 0) {session. flush (); Session. clear ();}}

(2) The statelesssession interface is used. It does not interact with level-1 and level-2 caches and does not trigger events. All operations through this interface are immediately sent to the database.

(32.16.use query.exe cuteupdate () in hibernateto Perform Batch update, the related level-2 cache is cleared.

10. Create a dynamic offline query in hibernate:

Datachedcriteria Dc = datechecriteria. forclass (the class to be queried. class); // Add the query condition DC. add (restrictions. eq ("name", name); Use Dynamic offline query: Criteria = dc. getexecutable (Session Object );

11. SQL query and naming query (namedquery) in hibernate ):

(1) When creating a query object in hibernate during SQL query, you can directly use the SQL statement as follows:

Session. createsqlquery (SQL statement );

SQL queries are often used in areas with high performance requirements, but are generally not recommended because compatibility with SQL statements affects program portability.

(2) namedquery is similar to the preparestatement object in JDBC. It is a pre-compiled query that can greatly improve the efficiency. The creation method is as follows:

Session. createnamedquery (hql query statement );

12. A small problem when using collections in hibernate:

When using a collection object in Hibernate and JPA, if list is used, a multibagexception exception is often reported during operations. The solution is as follows:

(1). the simplest and most convenient method: Use set instead of list.

(2) Add the @ cloumn or @ ordercloumn annotation to the field of the list set to specify a column index for the set.

13. hibernate cache:

Hibernate maintains two levels of cache:

(1) The internal cache, that is, the first-level cache, belongs to the transaction-level cache. In the session object lifecycle, each session maintains an independent cache, Which is exclusive to the current session instance. The internal cache is automatically maintained by hibernate. If manual intervention is required, you can use the following two methods:

A. session. evict: clears a specific object from the internal cache.

B. session. Clear: clears the internal cache.

(2). The second-level cache is shared by multiple session instances created in the current sessionfactory. In hibernate, the second-level cache covers application-level cache and distributed cache.

Cache in hibernate plays a role in the following situations:

A. When loading data through ID (primary key.

B. Delayed loading.

14. ibbench second-level cache:

(1) Introduction of hibernate second-level cache:

The application is deployed in the cluster environment.

(2). Conditions for using second-level cache:

A. data will not be modified by a third party.

B. The data size is within the acceptable range.

C. The data is read more than modified, that is, the data update frequency is relatively low.

D. Non-critical data can tolerate invalid data.

(3). Use the second-level cache provided by a third party for implementation:

Hibernate itself provides second-level cache implementation, but it has limited functions and is only used for development and debugging. Hibernate provides a third-party second-level cache implementation interface. The common second-level cache is as follows:

A. JCs. B. ehcache. C. Oscache. D. JBoss cache. E. swarmcache.

(4). cache synchronization policy:

The cache synchronization policy determines the access rules of Data Objects in the cache. In order to make cache transfer follow the correct application-level transaction isolation mechanism, when using the cache, you must specify the corresponding cache synchronization policy for each object. hibernate provides the cache synchronization policy in Step 4:

A. Read-Only: Read-only, for data that will not change.

B. nonstrict-read-write: Non-strict read/write, applicable to data that is not strictly required for synchronization and has a low update frequency.

C. read-write: strictly readable cache. Based on the timestamp judgment mechanism, the Read committed transaction isolation level is implemented for strict data synchronization. However, this policy does not support distributed caching, it is also the most used cache policy in practical applications.

D. Transactional: Transaction-type cache, which must run in the JTA environment. This policy achieves the Repeatable read transaction isolation level and is suitable for caching key data.

 

15. A small example of using second-level cache for hibernate:

(1) Enable Level 2 cache in hibernate:

Add the following parameters to the hibernate. cfg. xml configuration file (using ehcache as an example ):

<Hibernate-configuration> <session-factory> <! -- Specify the cache provider --> <property name = "hibernate. cache. provide_class"> net. SF. ehcache. hibernate. provider </property> ...... </Session-factory> ...... </Hibernate-configuration>

(2) configure the object ehcache implementation itself:

By default, the ehcache. xml file is added to the class path and the following configuration is added:

<Ehcache> <diskstore Path = "specify cache storage directory"> <defaultcache mexelementsinmemory = "10000" // The maximum number of data objects that can be stored in the cache: Eternal = "false" // Cache whether the data in is constant timetoidleseconds = "120" // cache data passivation time timetoliveseconds = "120" // when the cache data survival time overflowtodisk = "true" // when the memory is insufficient, enable hard disk cache/> </ehcache>

(3). Specify the cache synchronization policy:

Specify the cache synchronization policy in each object ing file and add the following:

<Class name = "hibernate object class full path"> <Cache Usage = "read-write"/> ...... <Set name = "…">. <Cache Usage = "read-only"/> </set> </class>

Note: cache synchronization policies can be used for object classes or set attributes.

16. Applicable and inapplicable scenarios of hibernate:

Since Object Relational ing (ORM) such as Hibernate is used to operate between objects and relational databases, it is necessary to convert object-oriented operations into SQL statements of local databases, there are some performance disadvantages. In addition, if you are familiar with hibernate, there may be n + 1 queries and delayed loading problems, so hibernate has its own suitable and unsuitable scenarios.

(1). Unsuitable scenarios:

A. Online Analytical Processing (OLAP): mainly involves a large number of queries.

B. Systems with sea data and demanding performance requirements.

(2). Applicable scenarios:

Online Transaction Processing (OLTP ).

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.