The complete use of Detachedcriteria and criteria in hibernate

Source: Internet
Author: User
Tags rowcount

The recent use of Spring and Hibernate in projects has made it easier to apply Criteria in the Query method

The design can be flexibly based on the characteristics of the criteria to facilitate the assembly of query conditions. Now summarize the use of the criteria for hibernate:
Hibernate designed the Criteriaspecification as the parent interface for criteria, and the criteria and Detachedcriteria are provided below.
The main difference between criteria and Detachedcriteria is that the form is created differently, the criteria are online,
It is created by the Hibernate session, while the Detachedcriteria is offline and is created without
Session,detachedcriteria provides 2 static methods Forclass (Class) or Forentityname (Name)
To create a Detachedcriteria instance. Spring's Framework provides a gethibernatetemplate
(). Findbycriteria (Detachedcriteria) method makes it easy to return query knots according to Detachedcriteria
Fruit.
Both criteria and Detachedcriteria can use criterion and projection to set query criteria. Can be set
Set Fetchmode (the mode of federated query fetching), setting the Sort method. You can also set Flushmodel for Criteria
(The way the session is washed) and Lockmode (Database lock mode).
Criterion and projection are described in detail below.
Criterion is the criteria for the criteria query. The Criteria provides an add (criterion criterion) method to
Add query criteria.
The main implementations of the criterion interface include: Example, Junction, and simpl**********. and
The actual use of Junction is its two subclasses conjunction and disjunction, respectively, using and and or manipulating
As a symbol to join the query criteria collection.
Criterion instances can be created by the restrictions tool class, restrictions provides a large number of static
methods, such as EQ (equals), GE (greater than equal), between, etc. to create criterion query criteria
(simpl********** instance). In addition, restrictions also provides a way to create conjunction and
Disjunction instance, by adding the query criteria to the Add (Criteria) method of the instance to form a collection of query criteria

As for the creation of Example, the Example itself provides a static method for creating (Object
entity), that is, based on an object (an object that is typically mapped to a database in actual use). You can then set some
Filter conditions:
Example exampleuser =example.create (u)
. IgnoreCase ()//Ignore case
. Enablelike (Matchmode.anywhere);
Attributes of type String, regardless of where the value is matched there. Equivalent to%value%
Project is primarily for the Criteria to make report queries, and to implement groupings. Project mainly has
Simpleprojection, Projectionlist, and property three implementations. where Simpleprojection and
The instantiation of the projectionlist is done by the built-in projections, such as AVG, COUNT, Max,
Min, sum can make it easy for developers to make statistical inquiries about a field.
The property is a setting for querying a field, such as through Porperty.forname ("color"). In
(New string[]{"Black", "Red", "write"}); You can create a Project instance. Pass
The Add (Project) method of the criteria is added to the query criteria.
Query using Criteria, mainly to clarify that Hibernate provides those classes and methods to meet the development
For the creation and assembly of criteria, here are a few uses:
1. Create a criteria instance
The Org.hibernate.Criteria interface represents a query for a particular persisted class. The session is the factory for the criteria instance.
Criteria crit = Sess.createcriteria (Cat.class);
Crit.setmaxresults (50);
List cats = Crit.list ();

2. Limit result set content
A separate query condition is an instance of the Org.hibernate.criterion.Criterion interface.

The Org.hibernate.criterion.Restrictions class defines a factory method that obtains some of the 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 logically.

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 a considerable number of built-in criterion types (restrictions subclasses), but it is particularly useful to allow

You 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 by the column alias of the entity being queried.
The property instance is another way to get a condition. You can create one by calling Property.forname ()

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. Result set Ordering
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. Association
You can use Createcriteria () to easily establish constraints between interrelated 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 the elements in the Kittens collection.
Next, the substitution pattern is also 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 collection returned by the first two queries saved by the cat instance is not conditionally filtered. If you want to get only

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 Correlation Crawl
You can use Setfetchmode () to define the semantics of dynamic association fetching at run time.

List cats = Sess.createcriteria (Cat.class)
. Add (Restrictions.like ("name", "fritz%"))
. Setfetchmode ("Mate", Fetchmode.eager)
. Setfetchmode ("Kittens", Fetchmode.eager)
. List ();

This query can crawl mate and kittens via an outer join.

6. Query sample
The Org.hibernate.criterion.Example class allows you to build a conditional query from 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 properties, identifiers, and associations are ignored. Properties with null values are excluded by default.
You can adjust the 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 the like for string comparisons
List results = Session.createcriteria (Cat.class)
. Add (example)
. List ();


You can even use examples to place conditions on the associated object.

List results = Session.createcriteria (Cat.class)
. Add (Example.create (CAT))
. Createcriteria ("mate")
. Add (Example.create (Cat.getmate ()))
. List ();


7. Projection (projections), aggregation (aggregation) and grouping (grouping)
Org.hibernate.criterion.Projections is an instance factory of projection. We call it by calling

Setprojection () applies projections 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 ();


It is not necessary to explicitly use "group by" in a conditional query. Some projection types are defined as grouped projections, and he

are also present in the SQL GROUP BY clause.

You can optionally assign an alias to a drop shadow so that the projection value is referenced by the constraint or sort. Here are two different types of

Implementation mode:

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 simply wrap a projection instance into a projection instance of another alias. Nutshell

When you add a projection to a projection list, you can assign an alias to 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 projections:

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 of a session scope, and you can use any session to

Execute 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. List ();
Txn.commit ();
Session.close ();


Detachedcriteria can also be used to represent subqueries. A conditional instance contains a subquery that can be passed subqueries or
Property obtained.

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 ();

It is also possible to associate subqueries with each other:

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.