The three major frameworks of Java_Web: the foundation of Hibernate + HQL, java_webhql

Source: Internet
Author: User
Tags web database

The three major frameworks of Java_Web: the foundation of Hibernate + HQL, java_webhql

12.1 HQL language basics
The Hibernate Query Language is HQL (Hibernate Query Language). You can directly use the object class name and attributes. The HQL syntax is similar to SQL, and has SQL keywords such as select, from, order by, count (), and where. The difference is that HQL is a completely object-oriented language that can directly query object classes and attributes.
12.1.1 HQL syntax
The HQL syntax is similar to SQL, and is a structure of select... from. Here, from is followed by the object class name, not the table name. Select can be followed by an object, or attributes or other values of an object, such:
Query query = session. createQuery ("select * from Users as users"); // Query all Users.
List list = query. list (); // executes the query and returns the List
Here, Users is the entity class Users, users is the Users object, and the keyword as usage is the same as SQL, which can be omitted. Query is a Hibernate query object. Query. list () returns the query result as a List. The preceding query can also be abbreviated:
Query query = session. createQuery ("from Users"); // Query all Users
List list = query. list (); // executes the query and returns the List
12.1.2 case sensitivity in HQL
HQL is case-insensitive. "select * from Users as users" can also write "SELECT * FROM Users as users ". However, the Java class name, package name, and attribute name must be case sensitive. Therefore, the Users must be consistent with the class name.
12.1.3 use the package name in the query
If the same entity class name does not exist in a project, the package of the entity class in the query statement can be omitted. Hibernate will be able to retrieve the actual t entity class based on the class name. However, if the object class name is the same, the package information must be included in the query; otherwise, Hibernate does not know which object class to use. The sample code of the query statement using the package name is as follows:
SELECT users FROM com.. java. vo. Users users
12.1.4 return type of query results
Hibernate uses a Query object for Query. The createQuery method of the Session can create a Query instance. The parameter is HQL. The Query object can return various types of Query results, such as long, String, List </font> Object Class Name>, List, And POJO. The most common query methods are uniqueResult () and list. UniqueResult () returns a single value, while list () returns zero or multiple values. The following describes uniqueResult () and list () respectively ().
1. uniqueResult () returns a single value
The unique () of Query returns a single object. When you use unique () to obtain the return value, the HQL statement can query only one result. If there are more than one result, the unique () method throws an exception. If not, null is returned. This method is often used to query the total number of records, because one object is always returned and there is only one. For example:
Query q = session. createQuery ("select count (*) from Users"); // create a Query object
Number num = (Number) q. uniqueResult (); // returns a single instance
Int count = num. intValue (); // return the value.
When querying the total number of queries, the HQL format must be "select count (*) from Users. The return value may be Short, Integer, Long, BigInteger, and Other types. The specific return type depends on the type of the primary key. The Number type of the parent class of all numeric types can be used here.
2. list () returns a set.
The list () method of Query is the most common method. In fact, the unique () method is executed after the list () method obtains the returned data. List () always returns a java. util. List object with zero or multiple values. List () can return an object, or an attribute or attribute of an object. For example:
List </span> Users> list1 = session. createQuery ("select * from Users"). list ();
List list2 = session. createQuery ("select users. name from Users users"). list ();
List nlist3 = session. createQuery ("select users. name, users. dept. name from Users users"). list ();
List </span> Users> list4 = session. createQuery ("select users. dept from Users users"). list ();
The first query returns the List of Users objects. The second query returns the List containing the Users name value (String type. The third query returns a List of strings (String [] type) consisting of Users name value and Users Dept name value. The fourth query returns the Dept List stored in Users. Although it is an attribute of Users, it is still of the Users type.
12.2 The query results return multiple objects at the same time
The list () method of Query returns the java. util. List object. List stores complete object class objects. For example, "select * from Users" will query all Users, including all instantly loaded attributes of the Users class.
For some queries, you only need to query several attributes, instead of all object class attributes. In this case, you can specify the part to be returned in HQL. When querying some attributes, the returned results are still of the List type, which may be a single Object, an array Object [], or a List Object and a Map Object. The type of data returned is determined by the HQL statement.
12.2.1 return List set
The returned results can also be placed in the List. During query, HQL adopts the form of "select new List (name1, name2, name3) from. You also need to traverse the List to obtain the returned List, and then traverse the returned List to obtain the query result. The instance code is as follows:
// Query the three fields, put them in a new List set, and return the list1 object of the List set.
List list1 = session. createQuery (
"Select new List (u. name, u. address, u. password) from Users u"). list ();
For (List li: list1) {// traverse the first List set
For (Object o: li) {// traverse the List set at the second layer (Save the set of three fields)
System. out. println ("" + o); // output Object
}
}
In the code above, put the queried fields in the query statement into the List set, and then put the results of the createQuery () Query into the List set. Through the for loop, the objects in the set are traversed twice.
12.2.2 returned Object array Object []
When multiple attributes are queried, Hibernate returns multiple objects at the same time (returned in Object [] type ). The returned array is placed in the List. The returned array needs to traverse the List object. The sample code is as follows:
List list = session. createQuery (
"Select u. name, u. address, u. password from Users u"). list (); // query multiple attribute values in Users and return list
For (Object [] obj: list) {// traverses the list set containing Arrays
For (Object object: obj) {// traverses the Array
System. out. println ("" + obj); // output the traversal result Object
}
}
The code above queries multiple attributes and returns an array. If only one attribute is queried, the array is not returned and the type of data is directly returned. For example, "select u. name from Users u" will return the List.
12.2.3 returns an object class Object
The object class object mentioned here refers to the Java object class object. If only some attributes are queried, it is convenient to return arrays, lists, and maps. However, operations on Object [] arrays, lists, and maps are not as convenient as operations on Object objects. Therefore, when querying some attributes, you can return object objects. Constructors can also be used in HQL. The sample code is as follows:
List </span> Users> list = session. createQuery (
"Select newUsers (u. name, u. password) from Users u"). list (); // use the Users class constructor in HQL
When using Users class constructor in HQL, the Users class must have a public Users (String name, String password) constructor. Hibernate calls this constructor to convert the returned values from the Object [] array to the Users Object class.
Note: When Using constructor in HQL, the corresponding object class must also have constructor with the same parameter features.
12.2.4 returned Map set
It is more practical to return the Map type. Map contains the queried column name and value. Traverse the List to obtain the Map. You can directly obtain the value from the Map, or traverse the Map, for example:
// Place the fields to be queried into the Map set, and return the queried Map set to the List set.
List map = session. createQuery (
"Select new Map (u. name as name, u. address as address, u. password as password )"
+ "From Users u"). list ();
For (Map map1: (List) map) {// traverses the List set
System. out. println ("Name:" + map1.get ("name"); // output the name attribute in the Map set
System. out. println ("Password:" + map1.get ("password"); // output the password attribute in the Ma set.
System. out. println ("Address:" + map1.get ("address"); // outputs the address attribute of the Map set.
}
12.3 advanced HQL applications
This section describes some common advanced applications in HQL, including conditional queries in HQL, querying results by PAGE, cascading queries, and other applications.
12.3.1 conditional Query
HQL uses the where clause to connect to a condition clause. The syntax is similar to that of SQL. Most SQL rules are applicable to HQL, such as equal to (=), greater than (>), and less than (</font>. The where clause of HQL uses the attributes of an object class or an attribute. The Query conditions can be written in HQL or set parameters through Query. The sample code is as follows:
Session. createQuery ("select * from Users"
+ "Where u. dept. name = null and u. age <: age ")
. SetParameter ("age", 23). list ();
The where clause of HQL can use the following operators:
Q mathematical operators: + ,-,*,/.
Q comparison operators: = ,! =, <>, >=, <=, And like.
Q logic calculation method: and, or, not.
Q SQL operators: in, not in, between, is null, is not null, is empty, number of, and so on.
Q string connection:... |... Or concat (...,...).
Q time and date functions: current_date (), current_time (), current_timestamp ().
Q: time and date functions: second (...), minute (...), hour (...), day (...), month (...), year (...).
Q JPA-defined operations: substring (), trim (), lower (), upper (), length (), locate (), abs (), sqrt (), bit_length (), coalesce (), nullif ().
Q Database supports SQL scalar functions: sign (), trunc (), rtrim (), and sin ().
Q simple jump statement: case... when... then... else... end.
For example, string connection:
List list = session. createQuery (
"Select u. name | 'Department | u. dept. name from Users u where u. dept! = Null "). list ();
In clause query:
List </span> Users> list = session. createQuery ("from Users where lower (trim (uu. name) in ('jack', 'macle', 'lily ')"). list ();
Set query:
List </span> Users> list = session. createQuery ("from Users u where size (u. events)> 5"). list ();
When setting query conditions, you should try to use setParameter () to pass parameters instead of writing them into HQL statements. When you execute an SQL statement for the first time, the database compiles the SQL statement for the next query. For queries with different parameters, the database directly calls the compiled SQL statement to improve the query efficiency.
12.3.2 statistical functions in HQL
Like SQL, Hibernate also provides a series of statistical functions. Hibernate converts the HQL statistical function to the function supported by the underlying database SQL.
Common statistical functions in SQL, such as count (), sum (), min (), max (), avg (), count (distinct ...) and so on can also be used in HQL, the syntax is the same as SQL, for example:
Number num = (Number) session. createQuery (
"Select count (*) from Users u where u. name! = Null ")
. UniqueResult ();
Int count = num. intValue ();
The total number of queries does not always return the Long type. The return value type is determined by the primary key type of the object class. If the primary key of an object class is of the short type, the return value may be of the Integer type.
12.3.3 HQL display query results by PAGE
Pagination is a required function of web database programs. Different databases use different paging methods. For example, MySQL uses limit and Oracle uses rownum. Hibernate hides all the details. You only need to set the current page number.
In paging display, the total number of records is queried first, and then the records displayed on this page are queried. Hibernate queries records through Query, queries sets the first record on the page through setFirstResult (), and sets the number of data on the page through setMaxResults (). The sample code is as follows:
// HQL paging Query
Query q2 = session. createQuery ("from Employees"); // Query all records
Int page = 1; // set the default page number to 1.
Q2.setFirstResult (page-1) * 2); // start number of each page
Q2.setMaxResults (5); // maximum number of pages displayed on each page
List emps = q2.list (); // returns the list set.
For (Employees emp: emps ){
System. out. println (emp. getEmployeeId (); // print the output attribute
}
Pagination is typically encapsulated as a Pagination component. Pagination is used to calculate the start record and total number of pages on each page. For more information about how to use the instance, see the Servlet section.
The total number of queries does not always return the Long type. The return value type is determined by the primary key type of the object class. If the primary key of an object class is of the short type, the return value may be of the Integer type.
12.3.4 cross-Table HQL Query
Table join is sufficient for cross-table queries. Hibernate supports the use of "." as an operator to obtain attributes. The usage is similar to the EL expression in JSP. Table join queries are applicable to non-set attributes. For cross-table queries, you only need to simply use attributes. For example, the Users name attribute and Dept name attribute. The sample code is as follows:
List </span> Users> list = session. createQuery (
"Select * from Users u where u. dept. name = 'java demo'"). list ();
On the surface, this query only involves the Users table, but in fact, because the where clause condition uses u. dept. name, the Dept table and Users table are queried.
12.3.5 HQL cascade Query
Cascade query is required for some queries. HQL supports SQL cascade queries, including inner join, left join, right join, and full join. Cascading query applies to set attributes, such as the dept set attribute of Users. For example, to query cat for "late" events in the events set attributes, the query statement is:
List </span> Users> list = session. createQuery (
"Select * from Users u left join u. events e where e. description like: description ")
. SetParameter ("description", "% late %"). list ();
12.3.6 Use Database SQL
HQL can be viewed as an encapsulation of All Database SQL statements. HQL provides the underlying database SQL support function. HQL only translates the function into the underlying SQL function. In some cases, the underlying database provides some function, but HQL may not support it. At this time, you can use the underlying SQL, which is technically called Native SQL ).
You cannot use Query when using database SQL queries. You must use a SQLQuery object. For example, query all the variables in the MySQL database:
SQLQuery sqlQuery = session. createSQLQuery ("show variables"); // use local SQL to query all variables
List list = sqlQuery. list (); // executes the query and places the query result in the List set.
For (Object [] object: list) {// traverses all attributes of the Set
System. out. println (object [0] + "," + object [1] + ","); // output object Property Value
}
Like Query, SQLQuery can also set parameters and display by page. The results returned by SQLQuery are of the List type. You can also set it to an object class so that the query results can be directly returned to an object class object. The sample code is as follows:
SQLQuery sqlQuery = session. createSQLQuery ("select * from users"); // use a local SQL query
SqlQuery. addEntity (Users. class); // you can specify the object class name in the brackets of the output type.
List <Users> list = sqlQuery. list (); // returns List <Users>
If the set object class is inconsistent with the query result, an exception is thrown.
12.3.7 configure name query using @ Annotation
Some queries are commonly used. You can name commonly used queries in Hibernate. You only need to reference the names when using the query. Naming queries are generally configured in object classes. You can use @ annotation to configure the name query and use XML to configure the name query.
When using the @ annotation to configure object classes, you must use the @ annotation to configure the name query. the Java annotation used is @ NamedQuery and @ NamedNativeQuery. Here, @ NamedQuery is used to configure the named HQL query, and @ NamedNativeQuery is used to configure the named underlying database SQL query. The code in the Entity class is as follows:
Import javax. persistence .*;
@ NamedQuery (name = "all users", query = "select * from Users") // name the query statement name.
@ NamedNativeQuery (name = "all users", query = "select * from users") // name the local query
@ Entity // Entity configuration
@ Table (name = "users") // Table Configuration
Public class Users {
// Content in the class is omitted here
}
In the above Code, the Users in the query statement named query is the name of the object class, and the users in the query statement named local query is the name of the database table.
12.3.8 extend the query using @ QueryHint
In the name query, you can use @ QueryHint to set JPA extension for the name query. The JPA specification allows some functional extensions of JPA to accelerate query performance and provide other functions. The sample code is as follows:
@ NamedQuery (name = "all users name", query = "select * from Users u where u. name =: name ", hints = {@ QueryHint (name =" org. hibernate. callable ", value =" true ")})
When @ QueryHint is used, write @ QueryHint in hints. The hints format is "hints = {}", and the @ QueryHint content to be written in braces. The Boolean value of org. hibernate. callable indicates whether the query is a stored procedure. Value = "true" indicates that the query is a stored procedure.
12.3.9 configure multiple name queries at the same time
Multiple @ NamedQuery cannot be configured for an object class. If you have multiple name queries, use the @ NamedQueries configuration. You can configure multiple @ NamedQueries in @ NamedQueries. The sample code is as follows:
@ NamedQueries (value = {
@ NamedQuery (name = "all users", query = "select u from Users u "),
@ NamedQuery (name = "users name", query = "select u from Users u where u. name =: name ",),
@ NamedQuery (name = "users for dept", query = "select u from Users u where u. dept. name =: dept ")})
When you need to use the name query, you can directly call it in the program. The program uses the name query in this way. If there are parameters, you need to set the parameters. The sample code is as follows:
Query query = session. getNamedQuery ("users name"). setParameter ("name", "Jack ");
List </span> Users> list = query. list ();
12.3.10 configure name query in XML
If the object class uses an XML file to configure the ing relationship, the name query must be configured in the hbm. xml Object Class ing file. For configuration of naming query, you must configure the name of the query after the entity class. You can configure the type of returned data. The sample code is as follows:

<? Xml version = "1.0"?> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 

 


12.4 summary of this Chapter
Hibernate enables the data persistence layer to program in an object-oriented way, directly store and operate Java objects, and use HQL to query data.

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.