Java programmers from stupid birds to cainiao (14th) detailed explanation on Hibernate (15th) hql and QBC query methods

Source: Internet
Author: User



First, let's take a look at several retrieval methods provided by hibernate:

1. navigation object graph Retrieval Method: navigate to other objects based on the loaded objects. For example, for a loaded customer object, call its getorders (). the iterator () method can be used to navigate to all associated order objects. If a delayed loading search policy is used at the association level, hibernate loads the associated order object from the database. Otherwise, it retrieves the order object from the cache.


2. OID Retrieval Method: searches for Objects Based on their oid. The get () and load () Methods of the session provide this function. If you know the oId in the application, you can use this method to retrieve objects.


3. hql Retrieval Method: hibernate provides the query interface, which is a dedicated hql query interface provided by hibernate. It can execute various complex hql query statements.


4. QBC Retrieval Method: Use the QBC (query by criteria) API to retrieve objects. This API encapsulates string-Based Query statements and provides more object-oriented interfaces.

The first two methods have been used many times. Now let's take a look at the hql retrieval method. Hql (Hibernate query language) is an Object-Oriented Query Language, which is similar to the SQL query language. Among the various retrieval methods provided by hibernate, hql is the most widely used retrieval method. It has the following features:


-Set various query conditions in the query statement

-Supports projection query, that is, only partial attributes of an object are retrieved.

-Paging query supported

-Support connection Query

-Supports grouping query and supports having and group by keywords.

-Provides built-in Aggregate functions, such as sum (), min (), and Max ()

-Supports subqueries, that is, embedded queries.

-Support dynamic parameter binding


The following example shows the hql retrieval procedure:

// Create a query object query = session. createquery ("from customer as c Where" + "C. name =: customername "+" and C. age =: customerage "); // dynamically binds the query parameter. setstring ("customername", "Tom"); query. setinteger ("customerage", 21); // execute the query statement and return the query result list result = query. list ();

From the above example, we can see that:

(1) create a query object through the createquery () method of the session, which contains an hql query statement. Hql query statements can contain named parameters. For example, "customername" and "customerage" are both named parameters.

(2) dynamically bind parameters. The query interface provides a method to assign values to various types of naming parameters. For example, the setstring () method is used to assign values to the mername naming parameters of the string type.

(3) Call the list () method of query to execute the query statement. This method returns the query results of the list type and stores the persistent objects that meet the query conditions in the list set.

Query also provides a good method of connection programming. by viewing the hibernate API, we can find that the returned value of the set method provided by the Query Class is still a query object, which can make the code more concise: for example.

List result=session.createQuery("……") .setString("customerName","Tom") .setInteger("customerAge",21) .list(); 

QBC

When using hql retrieval, you must define a string-based hql query statement in the application. The qbc api provides another method for retrieving objects. It consists of the Criteria interface, criterion interface, and expression class. It supports dynamic generation of query statements at runtime.

QBC retrieval steps:


1) Call the createcriteria () method of the session to create a criteria object.

2) Set query conditions. The expression class provides a series of static methods used to set query conditions. All these static methods return criterion instances, and each criterion instance represents a query condition. The add () method of criteria is used to add query conditions.

3) Call the list () method of criteria to execute the query statement. This method returns the query results of the list type and stores the persistent objects that meet the query conditions in the list set. The following is an example of how to query QBC:

// Create a criteria object Criteria = session. createcriteria (customer. class); // set the query conditions, and then add the query conditions to criteria. Criterion criterion1 = expression. like ("name", "T %"); Criterion criterion2 = expression. eq ("Age", new INTEGER (21); criteria = criteria. add (criterion1); criteria = criteria. add (criterion2); // execute the query statement and return the query result list result = criteria. list ();

For the above program code, when you run the criteria list () method, the SQL query statement executed by Hibernate is:

Select * from MERs where name like't % 'and age = 21;

Note: The expression class is a subclass of org. hibernate. criterion. restrictions, so you can replace it with this class. Criteria is also a method-connected programming style, because the return value of the add method is also criteria, just like the following code:

List result=session.createCriteria(Customer.class).add(Expression.like("name", "T%") .add(Expression.eq("age", newInteger(21)) .list(); 

Both the query and criteria interfaces provide methods for displaying query results by page:

-Setfirstresult (INT firstresult): Specifies the object from which to start retrieval. The firstresult parameter indicates the index position of the object in the query result. The starting value of the index position is 0. By default, the query and criteria interfaces start to retrieve the first object in the query result, that is, the object with the index position 0.

-Setmaxresult (INT maxresults): sets the maximum number of objects retrieved at a time. By default, the query and criteria interfaces retrieve all objects in the query results.

Paging query:

Hql retrieval:

Query query = session.createQuery("from Customer c order by c.name asc"); query.setFirstResult(0); query.setMaxResults(10); List result = query.list(); 

QBC Retrieval

Criteria = session. createcriteria (customer. class); criteria. addorder (// In criteria, the order method is provided. ASC ("name"); criteria. setfirstresult (0); criteria. setmaxresults (10); List result = criteria. list ()

We have a general understanding of the two query methods: hql statement and QBC. Let's take a look at the specific usage. First, let's take a look at hql.

During Normal queries, the hql statement is always "from Class Name". In this way, we want to query all the attributes of the corresponding object. When we only want to query several fields of the object class, rather than the object of the entire object class, we need to add the hql statement omitted earlier. For example, if the hql statement is select S. Name, S. Age from student s, it only queries the name and age attributes in the student table. Query is called. Objects are not returned in the list () method, because we only query partial attributes of objects. What is in the list set queried. In fact, each element in the list object is an array of object objects, and each array contains several fields of the query object. The data is just some free data. The field data we want to obtain can be traversed using the following method.

The Code is as follows:

The above situation can be solved in another way.However, the prerequisite for successful execution in this mode is,The student object class constructs a constructor that contains the name and age attributes.

Query query = session. createquery ("select new student (S. name, S. age) from student s "); List list = query. list (); For (INT I = 0; I <list. size (); I ++) {student = (student) list. get (I) system. out. println (student. getname () + "," + student. getage (); system. out. println (student. getcardid (); // null is returned here. This field is not queried by the database}

From the preceding hql statement, we can see that student objects are queried, rather than independent data. Note the hql statement writing. This method is definitely not supported in SQL statements.

Hql statement for internal join query: From team T join t. Student; this inner join statement means to allow the team table and student table for internal join query. Many people recall that there are no on statements. What are the query conditions? This is because the HBM file has already indicated the field connection relationship between tables, so it will automatically connect to on. Let's take a look at the automatically generated SQL statements.

The query statement automatically generated by Hibernate is:


The Hibernate configuration provides us with a formatting SQL statement configuration. If the SQL _format attribute is set to true, the formatted SQL statement is obtained as shown above.

In the internal connection query results, I had such a question at the beginning. The result set obtained by the connection query is the Union set of the two tables. Which object is the result set? Not student. Is it team. Originally, Hibernate had prepared this for us. When we call the list method to obtain the result set, the obtained set is actually a collection of object arrays. This array usually contains two objects, such as the preceding hql Statement, which is the collection of student objects and team object arrays. Let's take a look at the specific code implementation:

Query query = session.createQuery("from Team t join t.students");List list = query.list();for(int i = 0; i < list.size(); i++){Object[] obj = (Object[]) list.get(i);Team team = (Team)obj[0];Student student = (Student)obj[1];System.out.println(team.getTeamName());System.out.println(student.getName());}

The internal connection also hides an unknown secret. When we set the delay loading to true, that is, when we delay loading the corresponding object information, after the session is closed, we traverse the list set. Then you will find that the corresponding student information is loaded in the same way,In this case, the delayed loading information in the configuration file is overwritten by the internal connection query. The corresponding object information is loaded before the session is closed.

Set entity parameters in hql

Next, let's take a look at the setting of entity parameters in hql for hibernate. The so-called object parameter setting is to set parameters in hql statements when an operation is executed using hql statements, we used to deal with some basic data-type parameter settings. hibernate provides the corresponding set method. Next, let's look at an hql query in the example:

Team team=session.get(Team.class,1);Query query = session.createQuery("from student s where s.team=:team and s.age>20");

In this place, the query condition is that the team object corresponding to the student is equal to the one just found. The hibernateapi provides two ways to set parameters for this location. Let's take a look at them one by one:

1. First:

Query. setparameter ("team", team, hibernate. entity (Team. class). This method requires three parameters. The first parameter is the specified parameter. Here, the team parameter in the preceding hql statement is set, and the second parameter is the value of the Set parameter, the third parameter is a type data. hibernate provides a hibernate class which contains a large number of static tool methods, including the method entity for obtaining the type object.

2. Second:

Query. setentity ("team", Team): This method is simple and practical. We use this method most of the time. It is quite familiar with the set method for setting basic data types. Directly set the parameter name and parameter value.

It is worth noting that the hql statement here compares whether two objects are equal. In fact, at the bottom layer of hibernate, it is converted into a corresponding foreign key Association.

Filter:

Hibernateapi provides a filter method, which is the createfiter (object collection, string s) method. It has two parameters. The first parameter is the object to be filtered, that is, the set object. The second parameter refers to the filtering Statement, which is actually part of the hql statement: for example, the following code:

Query query = session.createFilter(team.getStudents(), "where age > 20");List<Student> list = query.list();

QBC: as a real method of object-oriented database operations, QBC provides a large number of ApisDatabase Operations and conditions,Let's take a look at the usage of its API based on a specific example:

// Increase the age limit by 12-30 Criteria = session. createcriteria (student. class ). add (restrictions. between ("Age", new INTEGER (12), new INTEGER (30); // adds the name condition restriction. Criteria = session whose name starts with T. createcriteria (student. class ). add (restrictions. like ("name", "T %"); // adds a range restriction. The name must be "Jerry", "spark ", A string [] names = {"Jerry", "spark", "Tom"} in "Tom"; Criteria = session. createcriteria (student. class ). add (restrictions. in ("name", names); // sort the queried data in ascending order of age and Criteria = session in descending order of cardid. createcriteria (student. class ). addorder (Order. ASC ("Age ")). addorder (Order. DESC ("cardid"); // execute the Data Query list <student> List = criteria. list ();
Related Article

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.