The full usage of the criteria in Hibernate criteria hibernate

Source: Internet
Author: User
Tags rowcount

Transferred from: http://www.360doc.com/content/090313/10/26262_2794855.html

1.Criteria

Hibernate has designed criteriaspecification as the parent interface for criteria, and the criteria and Detachedcriteria are provided below.

 

2,Detachedcriteria

The Spring Framework provides the gethibernatetemplate (). Findbycriteria (Detachedcriteria) method to easily return query results based on Detachedcriteria.

  Detachedcriteria provides 2 static methods Forclass (Class) or forentityname (Name) make the creation of the Detachedcriteria instance.

3. The difference betweenCriteria and Detachedcriteria

< Span class= "Apple-tab-span" > 1criteria and Detachedcriteria is that the form created is not the same, The Criteria is online, created by the Hibernate Session, and Detachedcriteria is offline and created without a session.

< Span class= "Apple-tab-span" > < Span class= "Apple-tab-span" > Crite Both Ria and Detachedcriteria can set query conditions using Criterion and Projection. You can set the Fetchmode (the mode of federated query fetching) and set the sorting method. For Criteria, you can also set Flushmodel (the way to flush sessions) and Lockmode (Database lock mode). Criterion and Projection are described in detail below.

4,criterion and Projection

A, concept

Criterion is the criteria query. The criteria provides the add (Criterion Criterion) method for adding a query condition. The main implementations of the Criterion interface include: Example, Junction, and SimpleExpression. The actual use of Junction is its two subclasses, conjunction and disjunction, which are joined by using the and and or operators to join the query condition collection.

B, create

Examples of Criterion can be Restrictions tool class to create, restrictions provides a number of static methods, such as EQ (equals), GE (greater than equals), between, and so on, to create Criterion query criteria (simpleexpression instance). In addition, restrictions provides a way to create conjunction and disjunction instances by adding query criteria to the instance's Add method to form a collection of query criteria. As for the creation of Example, the Example itself provides a static method of Create (object entity), which is created based on an object that is typically mapped to a database in the actual use. You can then set some filter conditions: Example exampleuser =example.create (u). IgnoreCase ()//Ignore case. Enablelike (Matchmode.anywhere); A property of type String, regardless of where the value is matched there. The equivalent of%value% Project is to allow Criteria to query the report, and to implement grouping. Project has three implementations of Simpleprojection, Projectionlist, and property. The instantiation of Simpleprojection and Projectionlist is done by the built-in projections, such as the AVG, COUNT, max, Min, sum provided, which makes it easy for developers to make statistical inquiries about a field.   property is a set of criteria for querying a field, such as through Porperty.forname ("color"). In (New string[]{"Black", "Red", "write"}); You can create a Project instance. Use the Add (Project) method of the criteria to add to the query criteria.

5, the application uses criteria to query, it is mainly clear that Hibernate provides those classes and methods to meet the development of query conditions in the creation and assembly,

Here are a few uses:

< Span class= "Apple-tab-span" > 1. Create a criteria instance the Org.hibernate.Criteria interface represents a query for a particular persisted class. The session is the factory of the criteria instance. Criteria crit = Sess.createcriteria (Cat.class); Crit.setmaxresults (50); List cats = Crit.list ();

2. Limiting the 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 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 (  Rest Rictions.eq ("Age", new integers (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 integers (1))  . Add (Restrictions.eq ("Age", New Integer (2))). Lis T (); Hibernate provides a considerable number of built-in criterion types (restrictions subclasses), but it is especially useful to allow you to 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 entity being queried. A property instance is another way to get a condition. You can create a property by calling Property.forname (). Property age = Property.forname ("Age"); List cats = Sess.createcriteria (Cat.class). Add (Restrictions.disjunction ()  . Add (Age.isnull ())  . Add (AGE.E Q (New integer (0)))  . Add (Age.eq (New Integer (1)))  . Add (Age.eq (New Integer (2))). Add (property.f ORName ("name"). In (new string[] {"Fritz", "Izi", "Pk"}). List ();

< Span class= "Apple-tab-span" > 3. Result set Ordering you can use Org.hibernate.criterion.Order to sort the results of the query. List cats = Sess.createcriteria (Cat.class). Add (Restrictions.like ("name", "f%"). AddOrder (ORDER.ASC ("name")). AddOrder (Order.desc ("Age")). Setmaxresults (). List (); List cats = Sess.createcriteria (Cat.class). Add (Property.forname ("name"). Like ("f%"). AddOrder (Property.forname (" Name "). ASC ()). AddOrder (Property.forname (" Age "). Desc ()). Setmaxresults (). List ();

4. Associations you can use Createcriteria () It is very easy to establish constraints between interconnected entities. List cats = Sess.createcriteria (Cat.class). Add (Restrictions.like ("name", "f%"). Createcriteria ("Kittens")  . Add (Restrictions.like ("name", "f%"). List (); Note 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 previous two queries saved by the cat instance is not pre-filtered by the condition. 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 associative fetching you can use Setfetchmode () to define the semantics of dynamic associative 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 fetch mate and kittens through an external connection.

6. Query Example

org.h The Ibernate.criterion.Example class allows you to construct 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. By default, a property with a value of NULL is excluded. You can adjust the example to make it more practical. Example Example = Example.create (cat). Excludezeroes ()    //exclude Zero valued properties. Excludeproperty ("C Olor ")//exclude the property named" Color ". IgnoreCase ()      //perform case insensitive String Compariso ns. Enablelike ();      //use like for string comparisons List results = Session.createcriteria (cat.class). Add (example). lis T (); 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 ();

< Span class= "Apple-tab-span" > 7. Projection (projections), aggregation (aggregation), and Grouping (grouping)

Org.hibernate.criterion.Projections is the instance factory of Projection. We project to a query by invoking the Setprojection () application. 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 (Pr Ojections.groupproperty ("Color")). List (); There is no need to explicitly use "group by" in a conditional query. Some projection types are defined as grouped projections, and they appear in the GROUP BY clause of SQL. You can choose to assign an alias to a projection so that the projected value is referenced by the constraint or sort. Here are two different implementations: 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 make it easy to wrap one projection instance into another alias's projectionExample. 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 the 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 ();

< Span class= "Apple-tab-span" > 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. The condition instance contains a subquery that can be obtained by 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 (); It is also possible to correlate sub-queries: 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 (); Supplement: Criteria.add (Expression.eq ("status", new Integer)); Criteria.add (expression.in ("status", Optparm.getquerystatus ()));

The full use of criteria in Hibernate criteria hibernate

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.