Bernate Reading Notes -- condition Query

Source: Internet
Author: User

Conditional queries are generally completed using the following three classes:

1. Criteria: indicates a query.

2. Criterion: represents a query condition.

3. Restriction: indicates the tool class of the query condition.

To perform a conditional query, follow these steps:

1. Obtain the Hibernate Session Object

2. Create a Criteria object as a Session object

3. Use Restriction's static method to create Criterion query Conditions

4. Add the Criterion query condition to the Criteria query.

5. Execute the Criterion list () method or the uniqueResult () method to return the result set.

Example:

 

1 public void query () {2 Session session = HibernateUtil. getSession (); 3 Transaction tx = session. beginTransaction (); 4 // use ctiteria to query conditions. 5 List list = session. createCriteria (Person. class) 6. add (Restrictions. eq ("id", 1) 7. list (); 8 for (Iterator iterator = list. iterator (); iterator. hasNext ();) {9 Person person = (Person) iterator. next (); 10 System. out. println (person. getName (); 11} 12}

 

 

The Criteria object does not have any data filtering function, but the program can filter data by combining multiple Criterion (each Criterion object represents a data filtering condition) into the Criteria object.

Criteria includes the following two methods:

SetFristResult (int firstResult): set the first row record returned by the query.

SetMaxResult (int maxResult): set the number of records returned by the query.

These two methods are used to query pages.

Criteria also includes the following common methods:

Add (Criterion criterion): adds query conditions.

AddOrder (Order order): adds a sorting rule.

 

1 List list = session. createCriteria (Person. class) 2. add (Restrictions. like ("name", "Li %") // Add query Condition 3. addOrder (Order. desc ("name") // sorts result sets. setMaxResults (50) // The maximum number of returned records is 50. list (); // return result set

 

 

The Criterion interface represents a query condition, which is generated by Restrictions. Restrictions is a tool class used to generate query conditions. Most of its methods are static methods.

 

I. Association

If you need to use the attributes of the correlated object to add query conditions, you should use the createCriteria method again for this attribute.

 

1 List list = session. createCriteria (Person. class) 2. createAlias ("myEvent", "e") 3. add (Restrictions. like ("e. title "," Emy of industry % ") 4. list ();

 

 

The second createCriteria returns a new Criteria instance, which references the myEvent Association attribute in the Person class. Title is an attribute in the MyEvent class.

Next, the replacement form is also very useful in some cases.

1 List list = session. createCriteria (Person. class) 2. add (Restrictions. like ("name", "Li %") 3. setFetchMode ("myEvent", FetchMode. JOIN) 4. list ();

 

The createAlias () method does not create a new Criteria instance. It only creates an alias for the associated object so that the following filter conditions can be filtered based on the associated object.

Ii. Dynamic Association

By default, the conditional query loads the associated entities based on the delayed loading policy specified by the ing file. To change the delayed loading policy in the conditional query, you can use setFetchMode () method. The setFetchMode () method accepts a FetchMode parameter.

DEFAULT: Use the delayed loading policy specified in the configuration file for processing.

JOIN: use external JOIN and pre-Initialize all associated entities

SELECT: Enable delayed loading. The system uses a separate select statement to initialize the associated entities. The second select statement is executed only when the associated entity is actually accessed.

Use external connection to capture Myevent.

 

3. projection, aggregation, and grouping

In conditional filtering of Hibernate, Projection is used to represent the Projection operation. Projection is an interface, and Projections is used as the Projection factory to generate the Projection object.

Once a Projection object is generated, you can use the setProjection (Projection projection) method to perform the Projection operation.

 

1         List list = session.createCriteria(Person.class)2                     .setProjection(Projections.projectionList()3                     .add( Projections.avg("age"))4                     .add(Projections.groupProperty("name")))5                     .list();

 

 

You do not need to explicitly use "group by" in a condition query ". Some projection types are defined as group projection. They also appear in the group by clause of SQL.

If we want to sort the attributes After grouping, We need to specify an alias for the projection operation. There are two ways to specify an alias for the projection operation.

1. Use the alias () method

1         List list = session.createCriteria(Person.class)2                .setProjection(Projections.alias(Projections.groupProperty("name"), "name"))3                .addOrder(Order.asc("age"))4                .list();

 

2. Use the as () method to specify an alias for itself

 

1         List list = session.createCriteria(Person.class)2                     .setProjection(Projections.groupProperty("name").as("name"))3                     .addOrder(Order.asc("age"))4                     .list();

 

You can also use Property. forName () to represent projection:

1         List list = session.createCriteria(Person.class)2                .setProjection(Projections.projectionList()3                .add(Property.forName("name")))4                .list();

 

 

4. Offline query and subquery

The offline query of conditional query is represented by DetachedCriteria. The DetachedCriteria class allows you to create a query outside the range of a session and execute it using any Session.

1 public void detachedCriteriaTest () {2 // define an offline query 3 DetachedCriteria query = DetachedCriteria. forClass (Person. class ). setProjection (Property. forName ("name"); 4 Session session = HibernateUtil. getSession (); 5 Transaction tx = session. beginTransaction (); 6 // execute offline query 7 List list = query. getExecutableCriteria (session ). list (); 8 9 for (Iterator iterator = list. iterator (); iterator. hasNext ();) {10 Person person Person = (Person) iterator. next (); 11 System. out. println (person. getName (); 12} 13}

 

In addition, DetachedCriteria can also represent subqueries. When we pass DetachedCriteria into Criteria as the query condition, DetachedCriteria becomes a subquery.

1 public void subQuery () {2 // define an offline query 3 DetachedCriteria query = DetachedCriteria. forClass (Person. class ). setProjection (Property. forName ("name"); 4 Session session = HibernateUtil. getSession (); 5 Transaction tx = session. beginTransaction (); 6 // execute subquery 7 List list = session. createCriteria (Person. class) 8. add (Property. forName ("name "). in (query) 9. list (); 10 for (Iterator iterator = list. iterator (); iterator. hasNext ();) {11 Person person Person = (Person) iterator. next (); 12 System. out. println (person. getName (); 13} 14}

 

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.