This article is a mirror article of machine translation, please click here to jump to the original article.

View: 16672|Reply: 0

[Source] The detailed usage of createCriteria is the QBC query in Hibernate

[Copy link]
Posted on 8/9/2017 2:26:13 PM | | |

Now let's say there is a Student class with id, name, age attributes
String hql = "from Student s";
As we used to do, we usually do
Query query = session.createQuery(hql);
Or if you want to search according to the conditions.
String hql = "from Student s where s.name like 'King%'"
Query query = session.createQuery(hql);
If you use QBC instead of HQL, then the code is:
Criteria criteria =session.createCriteria(Student.class);
Criterion criterion = Expression.like("name","king%");
I can't see it like this. Then we add the search condition to the age of 22.
HQL:
String hql = "from Student s where s.name like 'Wang%' and s.age= 22 ";
Query query = session.createQuery(hql);
List list = query.list();
QBC:
Criteria criteria =session.createCriteria(Student.class);
Criterion criterion1 = Expression.like("name","king%");
Criterion criterion2 = Expression.eq("age",newInteger(22));
criteria.add(criterion1).add(criterion2);
List list = criteria.list();


It looks a lot more cumbersome. But anyone who has done a project knows that when a module's business logic changes, it often has to rewrite SQL, and the most annoying and annoying thing is to take someone else's HQL or SQL.
If you use QBC, it greatly increases the readability and maintainability of the code.
It is important to note that the null value is the value
For example, when we want to find a Student object with a null name, we should write it like this
Criteria criteria =session.createCriteria(Student.class);
Criterion criterion = Expression.isNull("name");
criteria.add(criterion).list();
and using between... and time
Criteria criteria =session.createCriteria(Student.class);
Criterion criterion1 = Expression.ge("age",new Integer(20)); Lower limit
Criterion criterion2 = Expression.le("age",new Integer(25)); Ceiling
//这里也可以把上述两个条件添加到第三个条件里
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 of the commonly used 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()
equals = Expression.eq()
does not equal <>or!= Expression.ne()

Null is null Expression.isNull()
is notnull Expression.isNotNull()
Within the specified range betweenand Expression.between()
Not in the specified range not betweenand Expression.not(Expression.between())
Belonging to a collection in Expression.in()
Not part of a collection 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 represents a query for a specific persistence class. Session is the factory used to manufacture the Criteria instance.



Criteria crit = sess.createCriteria(Cat.class);


crit.setMaxResults(50);


List cats = crit.list();


2. Narrow the scope of the result set A query condition (Criterion) is an instance of the net.sf.hibernate.expression.Criterion interface. The class net.sf.hibernate.expression.Expression defines to get 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 logically grouped.

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 a lot of pre-made condition types (subclasses of Expressions). There is a particularly useful one that allows you to embed SQL directly.

List cats = sess.createCriteria(Cat.class)



                .add( Expression.sql("lower($alias.name) like lower(?)", "Fritz%", Hibernate.STRING))


                .list();  
where {alias} is a placeholder, it will be replaced by the line alias of the queryed entity. (Original: The {alias} placeholder with be replaced by the row alias of the queried entity.)


3. Sort the results You can use net.sf.hibernate.expression.Order to sort the result set.


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 that the second createCriteria() returns a new instance of Criteria, pointing to an element 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 instance of the Criteria. Note that the kittens collection class held by the Cat instance in the previous two queries is not pre-filtered by criteria! If you want to return only kittens that meet the criteria, 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 You can change the automatic fetching policy of association objects by setting FetchMode() 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 via outer join.


6. According to the Example queries net.sf.hibernate.expression.Example class, you can 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 properties, representation properties, and associations are all ignored. By default, null attributes are also excluded. You can adjust how the Example is applied. You can
to adjust how the 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 establish criteria for associated objects. List results = session.createCriteria(Cat.class) .add(Example.create(cat) )


.createCriteria("mate") .add(Example.create(cat.getMate())) .list();


The reference code is as follows:






Previous:LINQ left, right, and inner connections
Next:The difference between let and var definition variables in js
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com