HQL Query
HQL provides a very powerful feature, which is for persistent objects, with the acquisition of objects, without update,delete and insert operations. And the HQL is object-oriented, with inheritance, polymorphism and correlation characteristics.
from
clause:
The FROM clause is the simplest hql, such as from Student, and can also be written as select S from Student S. It simply returns all instances of the student class. It is important to note that the HQL statement is not case sensitive except for the names of Java classes and properties.
Select
clause:
Sometimes you do not need to get all the properties of an object, you can use the SELECT clause for property queries, such as select S.name from Student S.
Statistical function Query
Functions can be used in hql, often using the following functions:
Count (): Count the number of record bars.
Min (): The minimum value is calculated.
Max (): The maximum value is calculated.
SUM (): Sum.
AVG (): Averages.
example, to obtain the number of student instances, you can write the following HQL statement:
Select COUNT (*) from Student
Get the HQL statement of student mean age:
Select AVG (s.age) from Student as S
You can use distinct to remove duplicate data:
Select distinct s.age from Student as S
where
clause:
HQL also supports subqueries, which implement this mechanism through a WHERE clause. The WHERE clause allows the user to narrow the list range of instances to be returned. For example, the following statement returns all student instances with the name "Bill":
Query query = Session.createquery ("From Student as s where s.name= ' Bill '");
The expression allowed in the WHERE clause includes most of the cases that can be used in SQL.
Common operators
Math Operations: +,-,*,/
True and false comparison operation: =, >=, <=, <>,! =, like
Logical operation: And, or, not
String Connection: | |
SQL header functions: such as upper () and lower ()
If the query returns more than one record, you can use the following keywords to quantify
All: Represents all records.
Any: represents any one of all records.
Some: same as any.
In: is equivalent to any.
Exists: Indicates that the subquery will return at least one record.
For example, the following statement returns all class objects with a student age greater than 18
From Group G where 18<all (select S.age from g.students s)
The following statement returns a class that has one student in all students of the age equal to 22:
From Group g where is = any (select S.age from g.students s)
Or
From Group G where 22= some (select S.age from g.students s)
Or
From Group G where the (select S.age from g.students s)
Connection Query
Like SQL, HQL also supports connection queries such as internal connections, outer joins, and cross-joins:
INNER JOIN: Inner connection
Outer join: Left OUTER JOIN
Rigth outer join: RIGHT outer JOIN
Full join: Fully connected, but not commonly used
Order by
clauses
The query return list can be sorted by the properties of any returned class or component
From Student s ORDER by s.name ASC
Criteria Query
Way
When querying data, you often need to set query criteria. In SQL or HQL statements, query conditions are often placed in a WHERE clause. Here hibernate also supports criteria queries, which encapsulate query criteria as a criteria object. In practice, you can use the Createcriteria () method of the session to build a Org.hibernate.Criteria instance, and then add the specific query criteria to the criteria instance by adding the criteria. This allows programmers to query data without using SQL or even hql.
Common query restriction methods
The Restrictions.eq () method in the code represents equal, which is equal to the case. The restrictions class provides a query throttling mechanism. It provides a number of ways to implement query throttling
Restrictions.eq (): equal,=
Restrictions.alleq (): parameter is a map object, using Key/value for multiple equals, equivalent to multiple restrictions.eq () effects
RESTRICTIONS.GT (): Greater-than: >
restrictions.lt ():less-than:<
restrictions.le:less-equal:<=
Restrictions.between (): The between clause that corresponds to SQL.
Restrictions.like (): A LIKE clause that corresponds to SQL.
Restrictions.in (): The IN clause that corresponds to SQL.
Restrictions.and (): and relationship.
Restrictions.or (): or relationship.
Restrictions.isnull (): Determines whether the property is empty, returns true for NULL, or returns FALSE.
Restrictions.isnoynull (): Contrary to the above.
ORDER.ASC (): Sort Ascending According to the field that is passed in.
Order.desc (): On the contrary
Matchmode.exact: Exact match in string, equivalent to like ' value '
Matchmode.anywhere: String in the middle position, equivalent to like '%value% '
Matchmode.start: String at the front, equivalent to like ' value% '
Matchmode.end: String at the end, equivalent to like '%value '
Here are some examples of query limitations:
All student objects that are queried for student names with the T switch
Criteria Criertia = Session.createcriteria (Student. Class); Criteria.add (Restrictions.like ("name", "t%"));
== (Student) list.get (0);
Or:
Criteria Criertia = Session.createcriteria (Student. Class); Criteria.add (Restrictions.like ("name", "T",Matchmode.start)); = criteria.list (); = (Student) list.get (0);
Find all student objects for student names between Bill,jack and Tom
String[] names = {"Bill", "Jack", "Tom"}; = Session.createcriteria (Student. Class); Criteria.add (restrictions.in ("name", names)); = criteria.list (); = (Student) list.get (0);
Query for all student objects with age 22 or null (NULL)
Criteria Criertia = Session.createcriteria (Student. Class); Criteria.add (Restrictions.eq (new Integer)); Criteria.add (Restrictions.isnull ("age")); = criteria.list (); = (Student) list.get (0);
Query all student objects with student names beginning with the letter F and Sort by name in ascending order
Criteria Criertia = Session.createcriteria (Student. Class); Criteria.add (Restrictions.like ("name", "f%")); Criteria.addorder (ORDER.ASC ("name")); = criteria.list (); = (Student) list.get (0);
Note The method that calls ORDER.ASC should be the Criteria.addorder () method.
Connection Limits
The criteria query uses Fetchmode to implement connection restrictions. In the HQL statement, the FETCH keyword can be used to represent a pre-fetch (Eager fetching), as follows:
From Group G
Left JOIN Fetch g.students s
where g.name like '%2005 '
The same functionality can be done using the criteria API
Native SQL
Enquiry
A local SQL query refers to a query directly using the SQL language of the local database. This is useful for migrating the original SQL/JDBC program to hibernate applications. Creating a SQL-based query Native SQL queries is controlled through the SQLQuery interface, which is obtained by calling the Session.createsqlquery () method.
named SQL query
Similar to hql named queries, you can also define a local SQK query statement in a mapping file and then invoke a named SQL query like a named HQL query.
Hibernate
Middle Session Interface
1. Session
the Save () and persist () methods
the Save () method of the session turns a temporary object into a persisted object. It completes the following actions:
(1) The temporary object is added to the session cache to enter the persistence state.
(2) Select the identifier generator specified by the mapping file to assign a unique OID to the persisted object.
(3) plan to execute an INSERT statement.
The Save () method of the session is used to persist the temporary object. You should not pass a persisted object or a free object to the Save () method. If you pass a persisted object to the Save () method, the step save operation is superfluous. If the free object is passed to the Save () method, the OID is regenerated and saved once.
The persist () method of the session is similar to the Save () method and can also be used to turn temporary objects into persisted objects.
The difference between the persist () method and the Save () method is that the persist () method does not guarantee that the OID of the persisted object is immediately assigned, but that it is possible to assign a value to the OID when the session cleans up the cache. In addition, if you call the persist () method outside the bounds of a thing, the method does not plan to execute the INSERT statement. The Save () method plans to execute the INSERT statement whether it is outside or within the bounds of the object.
2. Session
the load () and get () methods
The load () and get () methods of the session can both load a persisted object from the database based on the given OID, the difference between the two methods is:
(1) The load () method throws a Org.hibernate.ObjectNotFoundException exception when there is no record in the database that corresponds to the OID, and the Get () method returns NULL.
(2) The Load method takes a configured load policy (default is lazy loading), while the Get () method ignores the configuration and always takes the immediate load method.
3. Session
the update () method
The update () method of the session turns a free object into a persisted object. It completes the following actions:
(1) The free object is added to the session cache to make it a persistent object.
(2) plan to execute an UPDATE statement.
When the update () method associates a free object, an exception is thrown if an object of the same OID already exists in the cache of the session.
4. Session
the Saveorupdate () method
The Saveorupdate () method of the session also contains the function of the Save () method and the update () method, calling the Save () method if the passed parameter is a temporary object, or calling the update () method if the passed in parameter is a free object. Hibernate determines whether a parameter is a temporary object or a free object, based on the Oid,version version property of the object.
5. Session
the merge () method
The merge () method of the session can copy the properties of a free object into a persisted object. The processing flow is as follows:
(1) Find a matching persisted object based on the OID of the free object to the session cache. If a matching persistence object is found, the properties of the free object are copied to the persisted object, an UPDATE statement is scheduled, and a reference to the persisted object is returned.
(2) If a persisted object that is consistent with the free object OID is not found in the session's cache, an attempt is made to load the persisted object from the database based on the OID. If a matching persisted object exists in the database, copy the properties of the free object into the persisted object you just loaded, plan to implement an UPDATE statement, and return a reference to the persisted object.
(3) If the or object is not present in the database, a new object is created, the property is assigned to the new object, the new object is persisted, and the new object's reference is finally returned.
The difference between merger () and Saveorupdate () is that the Meger () object is still in the off-pipe state after the call.
6. Session
the Delete () method
The delete () method of the session is used to delete a Java object from the database. The delete () method can either delete a persisted object or delete a free object. The process is as follows:
(1) If the passed-in parameter is a free object, the free object is first associated with the session, making it a persisted object. If the argument is a persisted object, the step is ignored.
(2) plan to execute a DELETE statement.
(3) Delete the object from the session cache, and the object goes into the delete state.
7, session of the replicate () method
The replicate () method of the session enables you to copy objects from one database to another database.
Hibernate
Retrieving Policies
Introduction: Hibernate session when you load a Java object, you can load other Java objects associated with the object into the cache so that the program is called in a timely manner. In some cases, however, we don't need to load too many useless objects into the cache, which can burst the memory and increase the number of accesses to the database. So in order to reasonably use the cache, Hibernate provides several search strategies for users to choose from.
Category: Immediate retrieval policy, deferred retrieval policy, left OUTER join retrieval policy
1. Immediate Retrieval Strategy
With an immediate retrieval strategy, the retrieved object, and a pair of multiple objects associated with the object, are loaded into the cache. The Get method of the session is used to retrieve the policy immediately.
Advantage: Frequently Used association objects can be loaded into the cache.
Cons: 1, memory consumption. 2. There are too many SELECT statements.
2. Delayed retrieval Strategy
With a deferred retrieval strategy, the contents of the associated object are not loaded. The associated object is not loaded until the associated object is called the first time. The deferred retrieval policy applies only to the Load method of the session when no association class operations are involved. Deferred retrieval policies can also be applied to operations such as get,list when associated class operations are involved. When working at the class level, the deferred retrieval policy, only the OID of the loaded class does not load other properties of the class, only accesses the database to load the content when the other property is accessed for the first time. (Here Cglib generated the class's proxy class) at the association level operation, deferred retrieval policy, loading only the class itself, do not load the associated class, until the first call to the associated object, only to load the associated object program mode is deferred loading policy. If you need to specify the use lazy load policy. In the configuration file, set <class> lazy=true,<set> lazy=true or extra (enhanced delay) <many-to-one> Lazy=proxy and No-proxy.
Pros: The program determines which classes and content are loaded, avoiding a lot of useless SQL statements and memory consumption.
Disadvantage: After the session is closed, the associated class object cannot be accessed. You need to make sure that the associated object is called before the Session.close method.
3. Left Outer connection search strategy
Using the left OUTER join search, you can use the SQL outer join query to load the associated object into the cache.
<set>fetch set to join,<many-to-one> fetch is set to join
Pros: The application is completely transparent to the application, regardless of whether the object is persisted or in a free State, and can easily navigate from one object to the object associated with it. 2. An outer join is used, and the number of SELECT statements is small.
Cons: You may load objects that your application does not need to access, wasting a lot of memory space. 2. Complex database table joins can also affect retrieval performance.
batch-size Properties:
Whether immediate or deferred retrieval, you can specify the number of associated queries, which requires the use of the Batch-size property to specify the number of associated queries to reduce the number of data retrieved in bulk.
Hibernate query (hql--hibernate query Language)