Use of Criteria in Hibernate

Source: Internet
Author: User

I recently used Spring and Hibernate for development in the project. I feel that Criteria is easy to use, the query method <br> can be flexibly designed to assemble query conditions according to the features of Criteria. Now we will summarize the usage of Hibernate Criteria: <br> Hibernate designed CriteriaSpecification as the parent interface of Criteria. The following provides Criteria and DetachedCriteria. <Br> the major difference between Criteria and DetachedCriteria is that the creation method is different. Criteria is online. <br> it is created by Hibernate Session, while DetachedCriteria is offline, no <br> Session is required during creation. DetachedCriteria provides two static methods: forClass (Class) or forEntityName (Name) <br> to create a DetachedCriteria instance. The Spring framework provides the getHibernateTemplate <br> (). findByCriteria (detachedCriteria) method, which can easily return the query result based on DetachedCriteria <br>. <Br> both Criteria and DetachedCriteria can use Criterion and Projection to set query conditions. You can set <br> FetchMode (the mode of joint query capture) and set the sorting mode. For Criteria, you can also set FlushModel <br> and LockMode (database lock mode ). <Br> the following sections describe Criterion and Projection in detail. <Br> Criterion is the query condition of Criteria. Criteria provides the add (Criterion criterion) method to <br> add query conditions. <Br> the Criterion interface mainly includes Example, Junction, and SimpleExpression. <Br> the actual use of Junction is its two sub-classes conjunction AND disjunction, which use and or operator <br> to join the query condition set. <Br> Criterion instances can be created using the Restrictions tool class. Restrictions provides a large number of static <br> methods, such as eq (equal to) and ge (greater than or equal) create Criterion query conditions for methods such as between <br> (SimpleExpression instance ). In addition, Restrictions also provides methods to create conjunction and <br> disjunction instances by adding (Criteria) to the instance) method to add query conditions to form a set of query conditions <br>. <Br> As for the creation of Example, Example itself provides a static method create (Object <br> entity ), it is created based on an object (usually the object mapped to the database in actual use. Then you can set some <br> filter conditions: <br> Example exampleUser = Example. create (u) <br>. ignoreCase () // ignore case sensitivity <br>. enableLike (MatchMode. ANYWHERE); <br> // a String-type attribute that matches the value wherever it is located. Equivalent to % value % <br> the Project mainly enables Criteria to query reports and implement grouping. Project has three major implementations: <br> SimpleProjection, ProjectionList, and Property. SimpleProjection and <br> ProjectionList are instantiated by built-in Projections, for example, avg, count, max, <br> min, and sum can make it easy for developers to perform statistical queries on a field. <Br> & nbsp; Property is used to set query conditions for a field, such as Porperty. forName (& #8220; color & #8221 ;). in <br> (new String [] {& #8220; black & #8221;, & #8221; red & #8221;, & #8221; write & #8221;}); you can create a Project instance. Use the add (Project) method of <br> criteria to add it to the query condition. <Br> when using Criteria for query, it is important to note that Hibernate provides the classes and methods to meet the development query conditions. <br> The following describes how to create and assemble the query conditions: <br> 1. create a Criteria instance <br> org. hibernate. the Criteria interface indicates a query of a specific persistent class. Session is the factory of the Criteria instance. <Br> Criteria crit = sess. createCriteria (Cat. class); <br> crit. setMaxResults (50); <br> List cats = crit. list (); <br> 2. restrict result set content <br> A separate query condition is org. hibernate. criterion. an instance of the Criterion interface. <Br> the org. hibernate. criterion. Restrictions class defines factory methods for obtaining some built-in Criterion types. <Br> List cats = sess. createCriteria (Cat. class) <br>. add (Restrictions. like ("name", "Fritz %") <br>. add (Restrictions. between ("weight", minWeight, maxWeight) <br>. list (); <br> constraints can be grouped by logic. <Br> List cats = sess. createCriteria (Cat. class) <br>. add (Restrictions. like ("name", "Fritz %") <br>. add (Restrictions. or (<br> & nbsp; Restrictions. eq ("age", new Integer (0), <br> & nbsp; Restrictions. isNull ("age") <br>. list (); <br> List cats = sess. createCriteria (Cat. class) <br>. add (Restrictions. in ("name", new String [] {"Fritz", "Izi", "Pk"}) <br>. add (Restrictions. disjunction () <Br> & nbsp ;. add (Restrictions. isNull ("age") <br> & nbsp ;. add (Restrictions. eq ("age", new Integer (0) <br> & nbsp ;. add (Restrictions. eq ("age", new Integer (1) <br> & nbsp ;. add (Restrictions. eq ("age", new Integer (2) <br>. list (); <br> Hibernate provides many built-in criterion types (Restrictions subclass ), however, it is particularly useful to allow <br> you to use SQL directly. <Br> List cats = sess. createCriteria (Cat. class) <br>. add (Restrictions. SQL ("lower ({alias }. name) like lower (?) "," Fritz % ", <br> Hibernate. STRING) <br>. list (); <br> {alias} placeholder should be replaced with the column alias of the queried object. <Br> A Property instance is another way to obtain a condition. You can call Property. forName () to create a <br> Property. <Br> Property age = Property. forName ("age"); <br> List cats = sess. createCriteria (Cat. class) <br>. add (Restrictions. disjunction () <br> & nbsp ;. add (age. isNull () <br> & nbsp ;. add (age. eq (new Integer (0) <br> & nbsp ;. add (age. eq (new Integer (1) <br> & nbsp ;. add (age. eq (new Integer (2) <br>. add (Property. forName ("name "). in (new String [] {"Fritz", "Izi", "Pk"}) <br>. list (); <B R> <br> 3. Result set sorting <br> you can use org. hibernate. criterion. Order to sort the query results. <Br> List cats = sess. createCriteria (Cat. class) <br>. add (Restrictions. like ("name", "F %") <br>. addOrder (Order. asc ("name") <br>. addOrder (Order. desc ("age") <br>. setMaxResults (50) <br>. list (); <br> List cats = sess. createCriteria (Cat. class) <br>. add (Property. forName ("name "). like ("F %") <br>. addOrder (Property. forName ("name "). asc () <br>. addOrder (Property. forName ("age "). desc () <br>. s EtMaxResults (50) <br>. list (); <br> 4. association <br> you can use createCriteria () to easily create constraints between correlated entities. <Br> List cats = sess. createCriteria (Cat. class) <br>. add (Restrictions. like ("name", "F %") <br>. createCriteria ("kittens") <br> & nbsp ;. add (Restrictions. like ("name", "F %") <br>. list (); <br> note that the second createCriteria () returns a new Criteria instance, which references elements in the kittens set. <Br> next, the replacement form is also useful in some cases. <Br> List cats = sess. createCriteria (Cat. class) <br>. createAlias ("kittens", "kt") <br>. createAlias ("mate", "mt") <br>. add (Restrictions. eqProperty ("kt. name "," mt. name ") <br>. list (); <br> (createAlias () does not create a new Criteria instance .) <Br> the kittens set returned by the previous two queries stored by the Cat instance is not pre-filtered by the condition. If you want to obtain only <br> qualified kittens, you must use returnMaps (). <Br> List cats = sess. createCriteria (Cat. class) <br>. createCriteria ("kittens", "kt") <br>. add (Restrictions. eq ("name", "F %") <br>. returnMaps () <br>. list (); <br> Iterator iter = cats. iterator (); <br> while (iter. hasNext () {<br> Map map = (Map) iter. next (); <br> Cat cat = (Cat) map. get (Criteria. ROOT_ALIAS); <br> Cat kitten = (Cat) map. get ("kt"); <br >}< br> <br> 5. dynamic Association crawling <br> you can use setFetchMode () to run Defines the semantics of Dynamic Association capture. <Br> List cats = sess. createCriteria (Cat. class) <br>. add (Restrictions. like ("name", "Fritz %") <br>. setFetchMode ("mate", FetchMode. EAGER) <br>. setFetchMode ("kittens", FetchMode. EAGER) <br>. list (); <br> This query can capture mate and kittens through external connections. <Br> 6. query Example <br> org. hibernate. criterion. Example class allows you to construct a conditional query using a given instance. <Br> Cat cat = new Cat (); <br> cat. setSex ('F'); <br> cat. setColor (Color. BLACK); <br> List results = session. createCriteria (Cat. class) <br>. add (Example. create (cat) <br>. list (); <br> Version attributes, identifiers, and associations are ignored. By default, null attributes are excluded. <Br> You can adjust Example to make it more practical. <Br> Example example = Example. create (cat) <br>. excludeZeroes () & nbsp; // exclude zero valued properties <br>. excludeProperty ("color") // exclude the property named "color" <br>. ignoreCase () & nbsp; // perform case insensitive string comparisons <br>. enableLike (); & nbsp; // use like for string comparisons <br> List results = session. createCriteria (Cat. class) <br>. ad D (example) <br>. list (); <br> You can even use examples to place conditions on the correlated object. <Br> List results = session. createCriteria (Cat. class) <br>. add (Example. create (cat) <br>. createCriteria ("mate") <br> & nbsp ;. add (Example. create (cat. getMate () <br>. list (); <br> 7. projections, aggregation, and grouping <br> org. hibernate. criterion. projections is the instance factory of Projection. We call <br> setProjection () to project a query. <Br> List results = session. createCriteria (Cat. class) <br>. setProjection (Projections. rowCount () <br>. add (Restrictions. eq ("color", Color. BLACK) <br>. list (); <br> List results = session. createCriteria (Cat. class) <br>. setProjection (Projections. projectionList () <br> & nbsp ;. add (Projections. rowCount () <br> & nbsp ;. add (Projections. avg ("weight") <br> & nbsp ;. add (Projections. max ("weight ")) <Br> & nbsp ;. add (Projections. groupProperty ("color") <br>. list (); <br> you do not need to explicitly use "group by" in a condition query ". Some projection types are defined as group projection. <br> they also appear in the group by clause of SQL. <Br> you can assign an alias to a projection so that the projection values are constrained or referenced by sorting. The following are two different <br> Implementation Methods: <br> List results = session. createCriteria (Cat. class) <br>. setProjection (Projections. alias (Projections. groupProperty ("color"), "colr") <br>. addOrder (Order. asc ("colr") <br>. list (); <br> List results = session. createCriteria (Cat. class) <br>. setProjection (Projections. groupProperty ("color "). as ("colr") <br>. addOrder (Order. asc ("colr") <br>. list (); <br> <B R> the alias () and as () methods can easily package a Projection instance into a Projection instance of another alias. In short, <br> when you add a projection to a projection List, you can specify an alias for it: <br> List results = session. createCriteria (Cat. class) <br>. setProjection (Projections. projectionList () <br> & nbsp ;. add (Projections. rowCount (), "catCountByColor") <br> & nbsp ;. add (Projections. avg ("weight"), "avgWeight") <br> & nbsp ;. add (Projections. max ("weight"), "maxWeight") <br> & nbsp ;. add (Projections. groupProperty ("color"), "color") <br>. AddOrder (Order. desc ("catCountByColor") <br>. addOrder (Order. desc ("avgWeight") <br>. list (); <br> List results = session. createCriteria (Domestic. class, "cat") <br>. createAlias ("kittens", "kit") <br>. setProjection (Projections. projectionList () <br> & nbsp ;. add (Projections. property ("cat. name ")," catName ") <br> & nbsp ;. add (Projections. property ("kit. name ")," kitName ") <br>. addOrder (Order. asc ("catName") <br>. addOrder (Order. asc ("kitName") <br>. list (); <br> you can also use Property. forName () indicates projection: <br> List results = session. createCriteria (Cat. class) <br>. setProjection (Property. forName ("name") <br>. add (Property. forName ("color "). eq (Color. BLACK) <br>. list (); <br> List results = session. createCriteria (Cat. class) <br>. setProjection (Projections. projectionList () <br> & nbsp;. Add (Projections. rowCount (). as ("catCountByColor") <br> & nbsp ;. add (Property. forName ("weight "). avg (). as ("avgWeight") <br> & nbsp ;. add (Property. forName ("weight "). max (). as ("maxWeight") <br> & nbsp ;. add (Property. forName ("color "). group (). as ("color") <br>. addOrder (Order. desc ("catCountByColor") <br>. addOrder (Order. desc ("avgWeight") <br>. list (); <br> 8. offline (detached) query and subquery <br> D The etachedCriteria class allows you to create a query outside the range of a session and use any Session to <br> execute it. <Br> DetachedCriteria query = DetachedCriteria. forClass (Cat. class) <br>. add (Property. forName ("sex "). eq ('F'); <br> // create a Session <br> Session session = .; <br> Transaction txn = session. beginTransaction (); <br> List results = query. getExecutableCriteria (session ). setMaxResults (100 ). list (); <br> txn. commit (); <br> session. close (); <br> DetachedCriteria can also be used to represent subqueries. The condition instance contains Subqueries that can be obtained through Subqueries or <br> Property. <Br> DetachedCriteria avgWeight = DetachedCriteria. forClass (Cat. class) <br>. setProjection (Property. forName ("weight "). avg (); <br> session. createCriteria (Cat. class) <br>. add (Property. forName ("weight ). gt (avgWeight) <br>. list (); <br> DetachedCriteria weights = DetachedCriteria. forClass (Cat. class) <br>. setProjection (Property. forName ("weight"); <br> session. createCriteria (Cat. class) <br>. add (Subqueries. geAll ("weight", weights) <br>. list (); <br> associated subqueries are also possible: <br> DetachedCriteria avgWeightForSex = DetachedCriteria. forClass (Cat. class, "cat2") <br>. setProjection (Property. forName ("weight "). avg () <br>. add (Property. forName ("cat2.sex "). eqProperty ("cat. sex "); <br> session. createCriteria (Cat. class, "cat") <br>. add (Property. forName ("weight ). gt (avgWeightForSex) <br>. list (); <br> supplement: <br> criteria. add (Expression. eq ("status", new Integer (status); <br> criteria. add (Expression. in ("status", optParm. getQueryStatus (); <br> <a href = "http://hi.baidu.com/1166824/blog/item/a66c053ef9e9ffea55e72338.html

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.