Hibernate (5)-Object-Oriented Query Language and lock

Source: Internet
Author: User

Hibernate maps tables in the database to our entity classes, so that we no longer have to write SQL languages. However, sometimes we still need to manually write Query statements for the special nature of queries. To solve this problem, the Hibernate framework provides us with an HQL (Hibernate Query Language) Object-Oriented Query Language, and QBC (Query by Criteria

) Fully object-oriented queries. Here we will briefly summarize how to compile ql statements for Object-Oriented queries.


I. the query language in the HQL and Hibernate frameworks is an Object-Oriented Query Language. It is very similar to SQL statements, that is, to change the tables in SQL statements into Entity names, you can change the field name to the attribute name. Other fields are similar. It mainly uses the Query object. You can use the list, iterate (multi-value), and uniqueResult (single value) attributes to return values. Below are several small examples:


1. fuzzy query + list iteration:

String key = "san"; Query query = session. createQuery ("FROM Student s where s. sname like? "); // HQL statement. Both the class name and attribute name are used to replace the table and field query. setParameter (0, "%" + key + "%") in the database. // The parameter index starts from 0. // Query. setString (0, "%" + key + "%"); List
 
  
Sts = query. list (); for (Student s: sts) {System. out. println (s. getSname ());}
 



2. iterate is equivalent to the iterator in the set. The Hibernate framework first queries all id values that meet the conditions, and then queries each record based on each id. In this way, when we query N-condition records, the framework helped us send N + 1 statements, which are the N + 1 questions that we often discuss. Here we can experiment with the actual example:

Query query = session.createQuery("from Student s");Iterator
 
   it = query.iterate();while(it.hasNext()){Student s = (Student)it.next();System.out.println(s.getSname());}
 


3. If the returned result is one, you can use the uniqueResult value to obtain it:


public static void testSelect8(Session session){Query query = session.createQuery("from Student s where s.sid=1");Student s = (Student)query.uniqueResult();System.out.println(s.getSname());}

4. Of course, Query objects also support update, delete, and insert operations, but these operations will immediately perform operations on the database data rather than the data in the cache. When caching is supported, data may conflict, so use it with caution.


Query query = session. createQuery ("update Student s set s. sname = 'zhangsan 123 'where s. sid = 1 "); int I = query.exe cuteUpdate (); if (I = 1) {System. out. println ("updated successfully ");}

5. Let's talk about the relationship between the two and the cache:


The iterate method supports caching by default. The iterate method also supports caching as long as the second-level cache is configured in our framework.


What about list? By default, cache is not supported. How can we make it support caching? Here we need our configuration. Let's take a look at the configuration that supports caching?


A, first you need to introduce the jar package and the corresponding xml configuration file, here the jar package and configuration file and the second-level cache jar package is the same: ehcache-1.2.3.jar, ehcache. xml


B. Enable query cache in hibernate. cfg. xml (note that it is not a second-level cache ):

 
 
  
True
 



C. Let the framework identify the cache component, which is the same as that in the second-level cache:

 
 
  
Org. hibernate. cache. EhCacheProvider     
 

After this configuration, list supports caching. This query cache supports both level-1 and level-2 queries.

2. QBC (Query by Criteria) is queried by using the Criteria object. It is more suitable for Query of indefinite parameters. Here is a simple example,


Criteria cra = session. createCriteria (Student. class); // _ match one character, % match multiple characters cra. add (Restrictions. like ("sname", "% s %"); cra. addOrder (Order. desc ("sid"); List
 
  
Sts = cra. list (); for (Student s: sts) {System. out. println (s. getSname ());}
 



The above two items are in the Hibernate framework. The object-oriented method of writing SQL statements is similar to that of SQL statements in general, but it is more object-oriented and easier to write some functions, we can choose to use it based on different situations.


3. Let's take a look at the lock mechanism in Hibernate. In this framework, the lock mechanisms include pessimistic locks and optimistic locks!

1. pessimistic lock: we cannot modify some data at the same time. Otherwise, data errors may occur. In the database, we can use the row-Level Lock select ...... For update. In the Framework, pessimistic locks are applied. Why is it a pessimistic lock? Because the chance of changing data at the same time is very small, and this lock is always added, it is a kind of identity of the pessimistic. It is called a pessimistic lock. Let's see how to use it!

When the LockMode. UPGRADE parameter is set, other transactions can query the data only after the current transaction is committed. The performance of this pessimistic lock is relatively low.

Account account = (Account) session. get (Account. class, 1, LockMode. UPGRADE );

2. Optimistic lock: in fact, it is to solve the problem of simultaneous modification of such data with an optimistic attitude. The solution is that there is no lock when the transaction occurs differently. if the transaction is synchronized, its lock will take effect. Therefore, it locks only when the probability is very small, so it is called an optimistic lock. Its performance is greatly improved.


A. Implementation Method: Timestamp and version number (implemented by the Hibernate framework)

B. Add the ptimistic-lock = "version" attribute to the data corresponding to the optimistic lock:


 
  
  
   
    
   
   
   
   
  
 

In this way, the Framework automatically calls the version number for us to manage optimistic locks. Very powerful. Especially for some data that requires security, such as the balance of bank cards.

In summary, it is a simple summary of Object-Oriented Query statements and locks in Hibernate. I feel that the functions of Hibernate are still very powerful. We need to constantly explore and study ......


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.