Full use of criteria in hibernate

Source: Internet
Author: User

In terms of design, you can flexibly assemble query conditions according to the features of criteria. Now we will summarize the usage of hibernate criteria:

Hibernate designs criteriaspecification as the parent interface of criteria. The following provides criteria and detachedcriteria
.
The main difference between criteria and detachedcriteria is that they are created in different forms. Criteria is online and
It is created by the hibernate session, while the detachedcriteria is offline and does not need to be created

Session, detachedcriteria provides two static methods: forclass (class) or forentityname (name)

Create a detachedcriteria instance. The Spring framework provides the gethibernatetemplate

(). The findbycriteria (detachedcriteria) method can easily return query results based on detachedcriteria.

Result.
Criteria and detachedcriteria both use criterion and projection to set query conditions. You can set

Set fetchmode (the Capture Mode of the joint query) and set the sorting mode. For criteria, you can also set flushmodel

And lockmode (database lock mode ).

The following describes criterion and projection in detail.

Criterion is the query condition for criteria. Criteria provides the add (criterion) method

Add query conditions.
The criterion interface mainly includes example, junction, and simpleexpression. While

The actual use of junction is its two sub-classes conjunction and disjunction, which use and or

To join the query condition set.
Criterion instances can be created through the restrictions tool class. Restrictions provides a large number of static

Method, such as eq (equal to), Ge (greater than or equal to), between, etc.

(Simpleexpression instance ). In addition, restrictions also provides methods to create conjunction and

Disjunction instance: adds query conditions to the add (criteria) method of the instance to form a set of query conditions.

.
As for the creation of example, example provides a static method, create (Object

Entity), which is created based on an object (usually the object mapped to the database in actual use. Then you can set some

Filter condition:
Example exampleuser = example. Create (u)
. Ignorecase () // ignore case sensitivity
. Enablelike (matchmode. Anywhere );
// For the string type attribute, the value matches wherever it is. Equivalent to % value %

Project mainly enables criteria to query reports and implement grouping. Projects mainly include

Simpleprojection, projectionlist, and property. Simpleprojection and

The instantiation of projectionlist is completed by built-in projections, such as the provided AVG, Count, Max,

Min and sum make it easy for developers to perform statistical queries on a field.
Property is the setting of query conditions for a field, such as using porperty. forname ("color"). In

(New String [] {"black", "red", "write"}); you can create a project instance. Pass

The add (Project) method of criteria is added to the query conditions.

When using criteria for query, it is important to note that hibernate provides the classes and methods to meet the requirements of development

The following describes how to create and assemble query conditions:

1. Create a criteria instance
The Org. hibernate. Criteria interface indicates a query of a specific persistent class. Session is the factory of the Criteria instance.
Criteria crit = sess. createcriteria (Cat. Class );
Crit. setmaxresults (50 );
List cats = crit. List ();
 
2. Restrict result set content
A separate query condition is an instance of the org. hibernate. criterion. Criterion interface.

The Org. hibernate. criterion. Restrictions class defines factory methods for obtaining some built-in criterion types.
List cats = sess. createcriteria (Cat. Class)
. Add (restrictions. Like ("name", "Fritz % "))
. Add (restrictions. Between ("weight", minweight, maxweight ))
. List ();

Constraints can be grouped by logic.
 
List cats = sess. createcriteria (Cat. Class)
. Add (restrictions. Like ("name", "Fritz % "))
. Add (restrictions. Or (
Restrictions. eq ("Age", new INTEGER (0 )),
Restrictions. isnull ("Age ")
))
. List ();
 
List cats = sess. createcriteria (Cat. Class)
. Add (restrictions. In ("name", new string [] {"fritz", "Izi", "Pk "}))
. Add (restrictions. disjunction ()
. Add (restrictions. isnull ("Age "))
. Add (restrictions. eq ("Age", new INTEGER (0 )))
. Add (restrictions. eq ("Age", new INTEGER (1 )))
. Add (restrictions. eq ("Age", new INTEGER (2 )))
))
. List ();
 
Hibernate provides many built-in criterion types (Restrictions subclass), but it is particularly useful to allow

You can use SQL directly.
 
List cats = sess. createcriteria (Cat. Class)
. Add (restrictions. SQL ("lower ({alias}. Name) Like lower (?) "," Fritz % ",

Hibernate. String ))
. List ();
 
The {alias} placeholder should be replaced with the column alias of the queried object.
A property instance is another way to obtain a condition. You can call property. forname () to create

Property.
 
Property age = property. forname ("Age ");
List cats = sess. createcriteria (Cat. Class)
. Add (restrictions. disjunction ()
. Add (age. isnull ())
. Add (age. eq (New INTEGER (0 )))
. Add (age. eq (New INTEGER (1 )))
. Add (age. eq (New INTEGER (2 )))
))
. Add (property. forname ("name"). In (New String [] {"fritz", "Izi", "Pk "}))
. List ();
 
3. sorting result sets
You can use org. hibernate. criterion. Order to sort the query results.
 
List cats = sess. createcriteria (Cat. Class)
. Add (restrictions. Like ("name", "F % ")
. Addorder (order. ASC ("name "))
. Addorder (order. DESC ("Age "))
. Setmaxresults (50)
. List ();
 
List cats = sess. createcriteria (Cat. Class)
. Add (property. forname ("name"). Like ("F % "))
. Addorder (property. forname ("name"). ASC ())
. Addorder (property. forname ("Age"). DESC ())
. Setmaxresults (50)
. List ();
 
4. Join
You can use createcriteria () to easily establish constraints between correlated entities.
 
List cats = sess. createcriteria (Cat. Class)
. Add (restrictions. Like ("name", "F % ")
. Createcriteria ("kittens ")
. Add (restrictions. Like ("name", "F % ")
. List ();


Note that the second createcriteria () returns a new criteria instance that references elements in the kittens set.
Next, the replacement form is also very useful in some cases.
 
List cats = sess. createcriteria (Cat. Class)
. Createalias ("kittens", "KT ")
. Createalias ("mate", "MT ")
. Add (restrictions. eqproperty ("KT. Name", "MT. Name "))
. List ();


(Createalias () does not create a new criteria instance .)
The kittens set returned by the previous two queries saved by the cat instance is not pre-filtered by the condition. If you want to only get

For eligible kittens, you must use returnmaps ().
 
List cats = sess. createcriteria (Cat. Class)
. Createcriteria ("kittens", "KT ")
. Add (restrictions. eq ("name", "F % "))
. Returnmaps ()
. List ();
Iterator iter = cats. iterator ();
While (ITER. hasnext ()){
Map map = (MAP) ITER. Next ();
Cat cat = (CAT) map. Get (criteria. root_alias );
Cat kitten = (CAT) map. Get ("KT ");
}

5. Dynamic Association crawling
You can use setfetchmode () to define the semantics of Dynamic Association crawling at runtime.
 
List cats = sess. createcriteria (Cat. Class)
. Add (restrictions. Like ("name", "Fritz % "))
. Setfetchmode ("mate", fetchmode. Eager)
. Setfetchmode ("kittens", fetchmode. Eager)
. List ();
 
This query can capture mate and kittens through external connections.
 
6. query example
The Org. hibernate. criterion. Example class allows you to construct a conditional query using a given instance.
 
Cat cat = new CAT ();
Cat. setsex ('F ');
Cat. setcolor (color. Black );
List Results = session. createcriteria (Cat. Class)
. Add (example. Create (CAT ))
. List ();


Version attributes, identifiers, and associations are ignored. By default, null attributes are excluded.
You can adjust example to make it more practical.
 
Example example = example. Create (CAT)
. Excludezeroes () // exclude zero valued properties
. Excludeproperty ("color") // exclude the property named "color"
. Ignorecase () // perform case insensitive string comparisons
. Enablelike (); // use like for string comparisons
List Results = session. createcriteria (Cat. Class)
. Add (example)
. List ();


You can even use examples to place conditions on associated objects.
 
List Results = session. createcriteria (Cat. Class)
. Add (example. Create (CAT ))
. Createcriteria ("mate ")
. Add (example. Create (Cat. getmate ()))
. List ();


7. Projections, aggregation, and grouping)
Org. hibernate. criterion. Projections is the project instance factory. We call

The setprojection () application projects to a query.
 
List Results = session. createcriteria (Cat. Class)
. Setprojection (projections. rowcount ())
. Add (restrictions. eq ("color", color. Black ))
. List ();
 
List Results = session. createcriteria (Cat. Class)
. Setprojection (projections. projectionlist ()
. Add (projections. rowcount ())
. Add (projections. AVG ("weight "))
. Add (projections. Max ("weight "))
. Add (projections. groupproperty ("color "))
)
. List ();


You do not need to explicitly use "group by" in a condition query ". Some projection types are defined as grouped projection.

They also appear in the SQL group by clause.

You can assign an alias to a projection so that the projection values are constrained or referenced by sorting. Below are two different

Implementation Method:
 
List Results = session. createcriteria (Cat. Class)
. Setprojection (projections. Alias (projections. groupproperty ("color"), "Colr "))
. Addorder (order. ASC ("Colr "))
. List ();



List Results = session. createcriteria (Cat. Class)
. Setprojection (projections. groupproperty ("color"). As ("Colr "))
. Addorder (order. ASC ("Colr "))
. List ();
 
The alias () and As () methods are used to easily package a projection instance to a projection instance of another alias. In short,

When you add a projection to a projection list, you can specify an alias for it:
 
List Results = session. createcriteria (Cat. Class)
. Setprojection (projections. projectionlist ()
. Add (projections. rowcount (), "catcountbycolor ")
. Add (projections. AVG ("weight"), "avgweight ")
. Add (projections. Max ("weight"), "maxweight ")
. Add (projections. groupproperty ("color"), "color ")
)
. Addorder (order. DESC ("catcountbycolor "))
. Addorder (order. DESC ("avgweight "))
. List ();


List Results = session. createcriteria (domestic. class, "cat ")
. Createalias ("kittens", "Kit ")
. Setprojection (projections. projectionlist ()
. Add (projections. Property ("cat. Name"), "catname ")
. Add (projections. Property ("kit. Name"), "kitname ")
)
. Addorder (order. ASC ("catname "))
. Addorder (order. ASC ("kitname "))
. List ();


You can also use property. forname () to represent projection:
 
List Results = session. createcriteria (Cat. Class)
. Setprojection (property. forname ("name "))
. Add (property. forname ("color"). eq (color. Black ))
. List ();

List Results = session. createcriteria (Cat. Class)
. Setprojection (projections. projectionlist ()
. Add (projections. rowcount (). As ("catcountbycolor "))
. Add (property. forname ("weight"). AVG (). As ("avgweight "))
. Add (property. forname ("weight"). Max (). As ("maxweight "))
. Add (property. forname ("color"). Group (). As ("color ")
)
. Addorder (order. DESC ("catcountbycolor "))
. Addorder (order. DESC ("avgweight "))
. List ();


8. Offline (detached) queries and subqueries
The detachedcriteria class allows you to create a query outside the range of a session and use any session

Run it.
 
Detachedcriteria query = detachedcriteria. forclass (Cat. Class)
. Add (property. forname ("sex"). eq ('F '));
// Create a session
Session session = .;
Transaction txn = session. begintransaction ();
List Results = query. getexecutablecriteria (Session). setmaxresults (100). List ();
Txn. Commit ();
Session. Close ();


Detachedcriteria can also be used to represent subqueries. You can use subqueries or

Property.
 
Detachedcriteria avgweight = detachedcriteria. forclass (Cat. Class)
. Setprojection (property. forname ("weight"). AVG ());
Session. createcriteria (Cat. Class)
. Add (property. forname ("weight). gt (avgweight ))
. List ();

Detachedcriteria weights = detachedcriteria. forclass (Cat. Class)
. Setprojection (property. forname ("weight "));
Session. createcriteria (Cat. Class)
. Add (subqueries. geall ("weight", weights ))
. List ();


Correlated subqueries are also possible:
 
Detachedcriteria avgweightforsex = detachedcriteria. forclass (Cat. class, "cat2 ")
. Setprojection (property. forname ("weight"). AVG ())
. Add (property. forname ("cat2.sex"). eqproperty ("cat. Sex "));
Session. createcriteria (Cat. class, "cat ")
. Add (property. forname ("weight). gt (avgweightforsex ))
. List ();

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.