Hibernate (v)--object-oriented query language and lock

Source: Internet
Author: User

Hibernate Does the mapping of tables and our entity classes in the database so that we don't have to write the SQL language anymore. But sometimes the specificity of the query, or we need to manually write query statements,Hibernate framework to solve this problem provides us with HQL(hibernate Query Language) Object-oriented query language, and QBC( query by Criteria Fully Object-oriented queries, here is a brief summary of how object-oriented to write QL statements.

One,HQL,Hibernate the query language in the framework, is an object-oriented query language, and the SQL statement is very similar to the SQL The table in the statement is changed to the entity name, the field is changed to the attribute name, and the other basic is similar. The main use of this object is Query. The return value can be evaluated using properties such as list, iterate (multi-valued),Uniqueresult(single value). Below are a few small examples:

1 , fuzzy query +list iteration:

 String key = "san" ; Query Query  = Session.createquery ("From Student s where s.sname like?"); // HQL statement.  Look inside. Use the class name and attribute name instead of the table and field in the database  query.setparameter (0, "%" +key+ "%"); //   // query.setstring (0, "%" +key+ "%");   list<student> sts = Query.list ();  for   (Student s:sts) {System.out.println  (S.getsname ()); }  

2,iteratehibernate The framework will first query all idid to query each record, so that we query n Condition records, the framework helps us to send Span lang= "en-US" >n+1n+1

= Session.createquery ("From Student S");                Iterator<Student> it = query.iterate ();        while (It.hasnext ()) {          = (Student) It.next ();          System.out.println (S.getsname ());      }  

3, the return result is one, you can use the uniqueresult value to obtain:

 Public Static void Testselect (Session session) {              = Session.createquery ("From Student s where s.sid=1");             = (Student) Query.uniqueresult ();      System.out.println (S.getsname ());  }  

4, of course, the Query object also supports Update,delete,insert, but these operations immediately manipulate the data in the database without manipulating the data in the cache, and when the cache is supported, Data may conflict, so use caution

Query query = session.createquery ("Update Student s set s.sname= ' 3,123 ' where s.sid=1" );         int i = query.executeupdate ();   if (I==1) {      System.out.println ("update succeeded");  }  

5, let's talk about the relationship between the two and the cache:

The iterate method supports caching by default, and the iterate method is supported as long as our framework is configured with level two cache support .

What about list? The default is not to support caching, how to let it support the cache, where we need to configure, here is a simple look at the cache-supported configuration it?

A, the first need to introduce the jar package and the corresponding XML configuration file, where the jar package and configuration file and the level two cache jar package is the same:e Hcache-1.2.3.jar,ehcache.xml

B, enable query caching in Hibernate.cfg.xml (note that it is not a level two cache):

<!---  <propertynamepropertyname= " Hibernate.cache.use_query_cache ">true</Property>  

C , let the framework identify the cache component, which is the same as in Level two cache:

<!---  <propertynamepropertyname= " Hibernate.cache.provider_class ">org.hibernate.cache.EhCacheProvider</Property  >     

after this has been configured, The list supports caching, which is supported for first-level queries and level two queries.

Two, QBC(query by criteria)is a more suitable case for indefinite parameter queries by using the criteria object, and here is a simple example

Criteria CRA = Session.createcriteria (Student.  Class);   // _ matches a character,   % matches multiple characters   cra.add (restrictions.like ("sname", "%s%"));  Cra.addorder (Order.desc ("Sid"));  List<Student> sts = cra.list ();    for (Student s:sts) {      System.out.println (S.getsname ());  

The top two are Hibernate frameworks, the writing of object-oriented SQL statements is similar to the writing of SQL statements in general, but more object-oriented, it is easier to write some functions, We can make different choices according to different circumstances.

  

Three, let's take a look here. the lock mechanism in Hibernate, in which the lock mechanism includes pessimistic lock and optimistic lock!

1 , pessimistic Lock: For some of the data we can not be modified at the same time, otherwise there will be data errors, in the database we could through row-level lock Select... The For update locks the data and avoids it. And in the frame is through the pessimistic lock. Why call it pessimistic lock? Since this is a very, very small chance of modifying the data at the same time, the lock has been added, so it is a pessimist's identity. So called pessimistic lock. Take a look at how to use it!

    Set the Lockmode.upgrade parameter, the other transaction is able to query the data only after the current transaction commits. The performance of this pessimistic lock is compared to the bottom.

Account Account = (account) Session.get (Account.class, 1, Lockmode.upgrade);

2 , optimistic Lock: In fact, the attitude of optimistic people to solve this data at the same time to modify the problem. The workaround is that when a transaction does not occur at the same time, there is no lock, and if the transaction synchronization occurs, its lock is in effect. So, it is only when the probability of a very small situation occurs when the lock, so called optimistic lock. Its performance has been greatly improved.

    a , implementation: Timestamp and version number ( implemented by the Hibernate framework)

b, add the ptimistic-lock= "version" property on the data that we need to increase the optimistic lock:

 <hibernate-mapping>        <!--optimistic-lock= "version" using optimistic lock -      <classname= "Com.bjpowernode.hibernate.pojo.Account"Table= "T_account"Optimistic-lock= "Version">          <IDname= "Aid"column= "Aid">              <Generatorclass= "Assigned"/>          </ID>                    <!--version Number field, where we need to add the corresponding Verget,set method to the corresponding Pojo class -          <versionname= "ver"column= "Version"></version>                    < Propertyname= "Money"/>      </class>  </hibernate-mapping>  

In this way, the framework automatically calls the version number for us to manage optimistic locking. The functionality is still very powerful. Especially for some data that is particularly secure, such as the balance of a bank card, etc.

In this paper, we summarize the object- oriented query statement in Hibernate and the simple summary of the lock. Hibernate function is still very powerful, we need to constantly dig, delve into ...

Hibernate (v)--object-oriented query language and lock

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.