Home > Java > javaTutorial > body text

Summarize the usage examples of DetachedCriteria and Criteria

零下一度
Release: 2017-06-01 09:11:40
Original
1956 people have browsed it

The editor below will bring you a brief discussion on how to use DetachedCriteria and Criteria (a must-read). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

In conventional Web programming, there are a large number of dynamic conditional queries, that is, the user freely selects certain conditions on the web page, and the program dynamically generates SQL statements based on the user’s selection conditions. , make a query.

For example, I remember that you can choose advanced query conditions in Facebook. This is a dynamic query. We can’t predict how many queries will be used. Writing it directly to our Dao layer is obviously not satisfactory to us. Meaning of plug

In response to this demand, for layered applications, the Web layer needs to pass a query condition list to the business layer object. After the business layer object obtains this condition list, it then takes out the conditions in sequence. , construct the query statement. One difficulty here is how to construct the condition list? Map is traditionally used, but this method has great flaws. The information that Map can convey is very limited. It can only convey name and value, but cannot convey what kind of conditional operation is to be performed, whether it is greater than, less than, like, or something else. , the business layer object must accurately grasp the implicit conditions of each entry. Therefore, once the implicit conditions change, the query construction algorithm of the business layer object must be modified accordingly. However, this change in query conditions is implicitly agreed, not restricted by the program code, so it is very error-prone.

DetachedCriteria can solve this problem, that is, in the web layer, programmers use DetachedCriteria to construct query conditions, and then pass this DetachedCriteria as a method call parameter to the business layer object. After the business layer object obtains the DetachedCriteria, it can directly construct the Criteria within the session scope and query it. In this regard, the construction of query statements has been completely moved to the web layer for implementation, while the business layer is only responsible for completing persistence and query encapsulation. It is completely decoupled from the construction of query conditions, which is perfect!

The main difference between Criteria and DetachedCriteria

is that the creation form is different. Criteria is online, so it is created by Hibernate Session is created, while DetachedCriteria is offline and does not require Session when creating.

Creation of DetachedCriteria

DetachedCriteria Provides 2 static methods to create DetachedCriteria instances.
forClass(Class)
forEntityName(Name)

Spring’s framework provides offline query Support, very simple to use those methods

Spring framework provides getHibernateTemplate().findByCriteria(detachedCriteria) method which can easily return query results based on DetachedCriteria. The subclass of Criteria is DetachedCriteria, which we can simply use.

After using these, we have to say that Restrictions

is a tool class for generating query conditions. The expression of Restrictions is as follows
HQL operator QBC operator meaning
= Restrictions.eq() is equal
<> Restrictions.ne() is not equal

 Restrictions.gt() 大于greater than 
= Restrictions.ge() 大于等于 greater than or equal 
< Restrictions.lt() 小于less than 
<= Restrictions.le() 小 于 等 于 less than or equal 
is null Restrictions.isnull() 等于空值 
is not null Restrictions.isNotNull() 非空值 
like Restrictions.like() 字符串模式匹配 
and Restrictions.and() 逻辑与 
and Restrictions.conjunction() 逻辑与 
or Restrictions.or() 逻辑或 
or Restrictions.disjunction() 逻辑或 
not Restrictions.not() 逻辑非 
in(列表) Restrictions.in() 等于列表中的某一个值 
not in(列表) Restrictions.not(Restrictions.in()) 不等于列表中任意一个值 
between x and y Restrictions.between() 闭区间 xy中的任意值 
not between x and y Restrictions.not(Restrictions..between()) 小于值X 或者大于值y
Copy after login

Criteria this It is also something that must be said. Translated, it means conditions, standards and the like! It’s almost the same as our offline one

So let’s take a look at the example

Check all the information in the User table

Ours We need to get our session object~~ Online query is similar to our Query, but more powerful!

 Criteria criteria = session.createCriteria(User.class);
 List users = criteria.list();
 Iterator iterator = users.iterator();
 while(iterator.hasNext()) {
  User user = (User) iterator.next();
  System.out.println(user.getId() + user.getName());   
 }
Copy after login

Criteria is just a container. If you want to set query conditions, just use the add() method to add the restrictions of Restrictions. For example, query data whose age is greater than 20 and less than 40. Although our SQL statements can also be completed, for better encapsulation and more code reuse, it is best not to write our SQL statements directly. Only after seeing the company's encapsulated code can I feel the incomparable power of our predecessors. , the flexibility of code reuse is very high! Here, we can pass unlimited Restrictions to encapsulate them, which is very convenient to use!

Criteria criteria = session.createCriteria(User.class);
criteria.add(Restrictions.gt("age", new Integer(20)));
criteria.add(Restrictions.lt("age", new Integer(40)));
List users = criteria.list();
Copy after login

You can also use logical combinations to query, such as combining the conditions that age is equal to (eq) 20 or (or) age is empty (isNull):

A separate query condition is An instance of the org.hibernate.criterion.Criterion interface.
The org.hibernate.criterion.Restrictions class defines factory methods for obtaining some built-in Criterion types.

List cats = sess.createCriteria(Cat.class)

 .add( Restrictions.like("name", "Fritz%") )

 .add( Restrictions.between("weight", minWeight, maxWeight) )

 .list();
Copy after login

Dynamic association crawling

Our crawling mode is in the form of 1-to-many association! Did you capture it?

You can use setFetchMode() to define the semantics of dynamic associated fetching at runtime

List cats = sess.createCriteria(Cat.class)

.add( Restrictions.like("name", "Fritz%") )

.setFetchMode("mate", FetchMode.EAGER)

.setFetchMode("kittens", FetchMode.EAGER)

.list();
Copy after login

This query can fetch mates and kittens through outer connections.

DetachedCriteria的关联查询

假设要通过stuName查询一个学生Student记录,可以如下:

DetachedCriteria dc = DetachedCriteria.forClass(Student.class);
dc.add(Restrictions.like("stuName", stuName, MatchMode.ANYWHERE));
Copy after login

如果要通过Student的Team的teamName查询一个Student记录,很多人都会这么写:

DetachedCriteria dc = DetachedCriteria.forClass(Student.class); 
dc.add(Restrictions.like("team.teamName", teamName, MatchMode.ANYWHERE));
Copy after login


遗憾的是上述程序报错,说是在Student中找不到team.teamName属性,这是可以理解的。那么如何通过teamName查找、、Student呢?

可以这么写:

DetachedCriteria dc = DetachedCriteria.forClass(Student.class); 
dc.createAlias("team", "t"); 
dc.add(Restrictions.like("t.teamName", teamName, MatchMode.ANYWHERE));
Copy after login

没错,就是要先建立team的引用,才能用team导航到teamName

Department和Employee是一对多关联,查询条件为: 名称是“department”开发部门,部门里面的雇员年龄大于20岁;

DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Department.class);
detachedCriteria.add(Restrictions.eq("name", "department"))
     .createAlias("employees", "e")
     .add(Restrictions.gt(("e.age"), new Integer(20)));
List list = this.getHibernateTemplate().findByCriteria(detachedCriteria);
Copy after login

投影(Projections)、聚合(aggregation)和分组(grouping)

org.hibernate.criterion.Projections是 Projection 的实例工厂。

我们通过调用setProjection()应用投影到一个查询。这个的意思就是查询哪一列的意思

用来进行聚合操作,和sql中的聚合类似.求和/求平均值/统计记录数/…等等.

还有用来获取获取对象的某些属性(表字段)或属性集合.正常情况下,查询返回的是对象或对象的集合.使用投影的话就可以只返回你需要的属性值.即Hibernate不把记录封装对象了,只返回你在投影中设置的属性的值(值的集合)的数组

List results = session.createCriteria(Cat.class)

 .setProjection( Projections.rowCount() )

 .add( Restrictions.eq("color", Color.BLACK) )

 .list()
Copy after login


List results = session.createCriteria(Cat.class)

 .setProjection( Projections.projectionList()

  .add( Projections.rowCount() )

  .add( Projections.avg("weight") )

  .add( Projections.max("weight") )

  .add( Projections.groupProperty("color") )

 )

 .list();
Copy after login

在一个条件查询中没有必要显式的使用 “group by” 。某些投影类型就是被定义为 分组投影,他们也出现在SQL的group by子句中。

可以选择把一个别名指派给一个投影,这样可以使投影值被约束或排序所引用。下面是两种不同的

实现方式:

List results = session.createCriteria(Cat.class)

 .setProjection( Projections.alias( Projections.groupProperty("color"), "colr" ) )

 .addOrder( Order.asc("colr") )

 .list();
Copy after login
List results = session.createCriteria(Cat.class)

 .setProjection( Projections.groupProperty("color").as("colr") )

 .addOrder( Order.asc("colr") )

 .list();
Copy after login

alias()和as()方法简便的将一个投影实例包装到另外一个 别名的Projection实例中。简而言之, 当你添加一个投影到一个投影列表中时 你可以为它指定一个别名:

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();
Copy after login

也可以使用Property.forName()来表示投影:

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();
Copy after login

DetachedCriteria类使你在一个session范围之外创建一个查询,并且可以使用任意的 Session来执行它。
也可以使用spring封装好的哦!

DetachedCriteria query = DetachedCriteria.forClass(Cat.class)

 .add( Property.forName("sex").eq(&#39;F&#39;) );

//创建一个Session

Session session = .;

Transaction txn = session.beginTransaction();

List results = query.getExecutableCriteria(session).setMaxResults(100).list();

txn.commit();

session.close();
Copy after login

也可以是作为子查询

DetachedCriteria avgWeight = DetachedCriteria.forClass(Cat.class)

 .setProjection( Property.forName("weight").avg() );

session.createCriteria(Cat.class)

 .add( Property.forName("weight).gt(avgWeight) )

 .list();
Copy after login

【相关推荐】

1. 浅谈php函数serialize()与unserialize()的使用方法

2. PHP sprintf() 函数使用方法详解

3. php session()函数使用方法详解

The above is the detailed content of Summarize the usage examples of DetachedCriteria and Criteria. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template