search
HomeJavajavaTutorialSummarize the usage examples of DetachedCriteria and Criteria

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

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());   
 }

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();

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();

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();

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));

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

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


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

可以这么写:

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

没错,就是要先建立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);

投影(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()


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();

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

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

实现方式:

List results = session.createCriteria(Cat.class)

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

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

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

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

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

 .list();

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();

也可以使用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();

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();

也可以是作为子查询

DetachedCriteria avgWeight = DetachedCriteria.forClass(Cat.class)

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

session.createCriteria(Cat.class)

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

 .list();

【相关推荐】

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!

Statement
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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.