"Hibernate Step by Step"--HQL Query entity object query

Source: Internet
Author: User

The previous article briefly introduced HQL it as Hibernate query language, encapsulated the basic SQL of all query operations, HQL can implement the database file additions and deletions, this article focuses on HQL entity object Query method.


first, the Entity object query


Entity object queries are the basis of HQL queries, and as an object query language, unlike SQL, the contents of a query string are replaced with the class name and the class's property name. This query method is relatively simple, as long as there is SQL Foundation, the use of HQL is very simple, but there are some problems to note that the query to obtain data is not a goal, need to consider how to write efficient query statements, this is the focus of discussion.


1.1 n+1 Problems
1.1.1 What is the n+1 problem

When I first heard this noun, doubts might be there, and I had never heard of the n+1 problem before, so what does it mean? N+1 means that there are N data in a table, then a n+1 SQL command is generated when fetching the n data, which is called n+1. Here 1 refers to the issue of a query ID list of statements, n refers to the ID issued by the N-SQL statement, loading related objects. This kind of query operation is very inefficient, often generated in the iterator, that is, if we convert the query results directly into an iterator, this problem occurs, the following code:

public void Testquery () {Session session=null;try{session=hibernateutils.getsession (); Session.begintransaction (); * * will appear n+1 problem, so-called n+1 worth is issued n+1 SQL statement *  * 1: Issue a Query ID list of the statement *  N: issued by the ID N SQL statement, loading the related object */iterator iter= Session.createquery ("from Student"). Iterate (), while (Iter.hasnext ()) {Student student= (Student) iter.next (); System.out.println (Student.getname ());} Session.gettransaction (). commit ();} catch (Exception e) {e.printstacktrace (); Session.gettransaction (). rollback (); Finally{hibernateutils.closesession (session);}}

The above query code will produce a n+1 problem, because the query is returned an iterator, so that does not produce a single SQL statement, which depends mainly on the query mechanism of iterator, which is to query the data from the cache, If the data does not exist in the cache then the data is first converted into memory, so a SQL query statement is issued at this point, so that an SQL statement is generated at each iteration. This is actually a mistake and can be optimized with other methods.


1.1.2 Avoid n+1 problems

The problem with n+1 is that because of the improper use of iterate, of course there are other ways to avoid this n+1 problem, here is a list method. The biggest difference between list and iterate is that the list puts the data in the cache, but does not take advantage of the cache, and by default the list emits SQL statements every time. You can use list to save data to the database before using iterate, so that iterate access to the data can be read from the cache, avoiding the n+1 problem, the code is as follows:

public void Testquery () {Session session=null;try{session=hibernateutils.getsession (); Session.begintransaction (); List Students=session.createquery ("from Student"). List (); System.out.println ("---------------------------------");/** * avoids n+1 problems *  * Because data is placed in the session's cache (first-level cache) after a list operation So when using iterate * First issue a query ID list of statements, and then load the corresponding data according to the ID to the cache, if there is data matching in the cache * will not issue the SQL statement based on the ID query, directly using the data in the cache *  * Iterate method if there is data in the cache, it can improve performance, otherwise n+1 problem *///can use as alias iterator Iter=session.createquery ("from Student"). Iterate (); while (Iter.hasnext ()) {Student student= (Student) iter.next (); System.out.println (Student.getname ());} Session.gettransaction (). commit ();} catch (Exception e) {e.printstacktrace (); Session.gettransaction (). rollback (); Finally{hibernateutils.closesession (session);}}


The above example avoids the n+1 problem, because the list operation will put the data into the session cache (first-level cache), so when the use of iterate will be issued a query ID list of the statement, and then the ID to the cache to load the corresponding data, If there is data in the cache that matches, the SQL statement that is queried by the ID is no longer emitted, and the data in the cache is used directly. Iterate method if there is data in the cache, it can improve performance, otherwise there is a n+1 problem.


1.2 Object navigation Query


Object navigation is the data that gets to another object in one object by its property navigation, which simplifies the query statement and optimizes the query method. If we could rewrite the object of writing another class in our usual way, it would be cumbersome to get another object's operation, and the object navigation comparison statement.

@SuppressWarnings ({"Unchecked", "rawtypes"}) public void TestQuery1 () {Session session=null;try{session= Hibernateutils.getsession (); session.begintransaction ();//Returns the result set attribute list, the element type and the attribute type in the entity class are consistent list students= Session.createquery ("from Student s where s.classes.name like '%2% '"). List (); for (Iterator Ite=students.iterator (); Ite.hasnext ();) {Student obj= (Student) ite.next (); System.out.println (Obj.getname ());} Session.gettransaction (). commit ();} catch (Exception e) {e.printstacktrace (); Session.gettransaction (). rollback (); Finally{hibernateutils.closesession (session);}}

The query statement in the above example uses the method of object navigation, the query statement is the information from the student object, but the object property of the pair is from the Name property of the Classes object, the Query method using object navigation will obviously improve the query efficiency, optimize the query statement, It can be complicated to make a lot of connection statements if you change the normal query method.


second, SQL native query


The native query value is the use of SQL statements to query the acquisition of data, instead of using the HQL statement, it is actually very simple to use, similar to HQL, only need to use the Createsqlquery method query, it is similar to hql CreateQuery method, the code is as follows:

public void Testqeury () {Session session=null;try{session=hibernateutils.getsession (); Session.begintransaction (); List List=session.createsqlquery ("SELECT * from T_student"). List (), for (Iterator Ite=list.iterator (); Ite.hasnext ();) {object[] obj= (object[]) ite.next (); System.out.println (obj[0]+ "," +obj[1]);} Session.gettransaction (). commit ();} catch (Exception e) {e.printstacktrace (); Session.gettransaction (). rollback (); Finally{hibernateutils.closesession (session);}}

The above code uses the Createsqlquery method, the query string inside the method is the SQL statement, it implements the underlying string query method, the difference is that the HQL has done a layer of packaging, in the Hibernate.cfg.xml to configure the corresponding dialect options to complete the mapping.


Conclusion


Object query methods are HQL different from SQL, and can be distinguished when used. This article mainly discusses the problem of object query and Query method, and also adds the use of SQL original Query method. The next article will discuss HQL connection queries and statistical queries in detail.


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.