Detailed usage of createcriteria in hibernate, that is, QBC Query

Source: Internet
Author: User

Assume that there is a student class with the ID, name, and age attributes.
String hql = "from student s ";
According to the previous practice, we usually
Query query = session. createquery (hql );
Or you need to search by condition.
String hql = "from student s where S. name like 'wang % '"
Query query = session. createquery (hql );
If QBC is used without hql, the code is:
Criteria = session. createcriteria (student. Class );
Criterion criterion = expression. Like ("name", "Wang % ");
We can't see this. Then we add the search condition to the age of 22.
Hql:
String hql = "from student s where S. name like 'King % 'and S. Age = 22 ";
Query query = session. createquery (hql );
List list = query. List ();
QBC:
Criteria = session. createcriteria (student. Class );
Criterion criterion1 = expression. Like ("name", "Wang % ");
Criterion criterion2 = expression. eq ("Age", newinteger (22 ));
Criteria. Add (criterion1). Add (criterion2 );
List list = criteria. List ();

It looks complicated. however, people who have worked on projects know that when the business logic of a module changes, they often need to rewrite the SQL statements. The most annoying and annoying thing is holding others' hql or SQL statements, what should I modify at the bottom of the Two-eyed garden?
If QBC is used, the code readability and maintainability are greatly increased.
Note that the value of null
For example, this should be the case when we want to find the student object whose name is null.
Criteria = session. createcriteria (student. Class );
Criterion criterion = expression. isnull ("name ");
Criteria. Add (criterion). List ();
And when using between... and
Criteria = session. createcriteria (student. Class );
Criterion criterion1 = expression. Ge ("Age", new INTEGER (20); // lower limit
Criterion criterion2 = expression. Le ("Age", new INTEGER (25); // Upper Limit
// You can add the preceding two conditions to the third condition.
Criterion criterion3 = expression. And (criterion1, criterion2 );
Criteria. Add (criterion3). List ();
Equivalent to from student s where S. Age between 20 and 25
Equivalent to from student s where S. age> = 20 and S. age <= 25

The following is a comparison between common query conditions of hql and QBC.
Expression meaning hql QBC
Greater than or equal to> = expression. Ge ()
Greater than> expression. gt ()
Less than or equal to <= expression. Le ()
Less than <expression. LT ()
Equal to = expression. eq ()
Not equal to <> or! = Expression. Ne ()

Is null expression. isnull ()
Is notnull expression. isnotnull ()
Betweenand expression. Between () within the specified range ()
Not in the specified range not betweenand expression. Not (expression. ())
Belongs to a set in expression. In ()
Does not belong to a collection of notin expression. Not (expression. In ())
And expression. And ()
Or expression. Or ()
Not expression. Not ()
Fuzzy query like expression. Like


1. Create a criteria instance. net. SF. hibernate. criteria. This interface is used to query a specific persistence class. Session is a factory used to create a criteria instance.

Criteria crit = sess. createcriteria (Cat. Class );

Crit. setmaxresults (50 );

List cats = crit. List ();

2. Narrow the result set range. A Query condition (criterion) is an instance of the net. SF. hibernate. expression. Criterion interface. Class net. SF. hibernate. expression. expression defines some built-in criterion types.

List cats = sess. createcriteria (Cat. Class)

. Add (expression. Like ("name", "Fritz % "))

. Add (expression. Between ("weight", minweight, maxweight ))

. List ();

Expressions can be grouped by logic.

List cats = sess. createcriteria (Cat. Class)

. Add (expression. Like ("name", "Fritz % "))

. Add (expression. Or (expression. eq ("Age", new INTEGER (0), expression. isnull ("Age ")))

. List ();

List cats = sess. createcriteria (Cat. Class)

. Add (expression. In ("name", new string [] {"fritz", "Izi", "Pk "}))

. Add (expression. disjunction ()

. Add (expression. isnull ("Age "))

. Add (expression. eq ("Age", new INTEGER (0 )))

. Add (expression. eq ("Age", new INTEGER (1 )))

. Add (expression. eq ("Age", new INTEGER (2 )))))

. List ();

There are many pre-fabricated condition types (Child classes of expression ). It is particularly useful for you to embed SQL directly.

List cats = sess. createcriteria (Cat. Class)

. Add (expression. SQL ("lower ($ alias. Name) Like lower (?) "," Fritz % ", hibernate. String ))

. List ();
{Alias} is a placeholder, which is replaced by the row alias of the queried object. (Original: The {alias} placeholder with be replaced by the row alias of the queried entity .)

3. You can use net. SF. hibernate. expression. Order to sort the results.

List cats = sess. createcriteria (Cat. Class)

. Add (expression. Like ("name", "F % ")

. Addorder (order. ASC ("name "))

. Addorder (order. DESC ("Age "))

. Setmaxresults (50)

. List ();

4. Associations you can use createcriteria () between associations to easily specify constraints between entities with relationships.

List cats = sess. createcriteria (Cat. Class)

. Add (expression. Like ("name", "F % ")

. Createcriteria ("kittens ")

. Add (expression. Like ("name", "F % ")

. List ();

Note: The second createcriteria () returns a new criteria instance pointing to the elements of the kittens collection class. The following alternative forms are useful in specific situations.

List cats = sess. createcriteria (Cat. Class)

. Createalias ("kittens", "KT ")

. Createalias ("mate", "MT ")

. Add (expression. eqproperty ("KT. Name", "MT. Name "))

. List ();

(Createalias () does not create a new criteria instance .) Note that the kittens collection classes held by the cat instance in the previous two queries are not pre-filtered by criteria! If you want to return only kittens that meet the condition, you must use returnmaps ().

List cats = sess. createcriteria (Cat. Class)

. Createcriteria ("kittens", "KT ")

. Add (expression. 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 fetching can be used to change the automatic acquisition policy of the correlated object through setfetchmode () at runtime.


List cats = sess. createcriteria (Cat. Class)

. Add (expression. Like ("name", "Fritz % "))

. Setfetchmode ("mate", fetchmode. Eager)

. List ();

This query will get both mate and kittens through outer join.

6. The example query (example queries) net. SF. hibernate. expression. Example class allows you to create query conditions from the specified instance.

Cat cat = new CAT ();

Cat. setsex ('F ');

Cat. setcolor (color. Black );

List Results = session. createcriteria (Cat. Class)

. Add (example. Create (CAT ))

. List ();
Version attribute, indicating that the character attributes and associations are ignored. By default, null attributes are excluded. You can adjust how the example is applied. You can
To adjust how the example (example) is applied. 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 create criteria for the associated object. List Results = session. createcriteria (Cat. Class). Add (example. Create (CAT ))

. Createcriteria ("mate"). Add (example. Create (Cat. getmate (). List ();

The reference code is as follows:

String[] aa = new String[2];List results = getSession().createCriteria("base.database.entity.Menu").add(Example.create(instance)).add(Restrictions.between("date",new Date(),new Date())).add(Restrictions.or(Expression.eq("flg", "S"), Expression.eq("FLG", "D"))).add(Restrictions.in("flg", aa)).addOrder(Order.asc("menuOrder")).list();add(Projections.groupProperty("color"))

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.