hibernate示例

Welcome to the Hibernate Criteria Example Tutorial. Today we will look into Criteria in Hibernate.

欢迎使用Hibernate Criteria示例教程。 今天,我们将研究Hibernate中的条件。

Hibernate标准 (Hibernate Criteria)

Most of the times, we use HQL for querying the database and getting the results. HQL is not preferred way for updating or deleting values because then we need to take care of any associations between tables.

大多数时候,我们使用HQL来查询数据库并获取结果。 HQL不是更新或删除值的首选方法,因为这样我们就需要注意表之间的任何关联。

Hibernate Criteria API provides object oriented approach for querying the database and getting results. We can’t use Criteria in Hibernate to run update or delete queries or any DDL statements. Hibernate Criteria query is only used to fetch the results from the database using object oriented approach.

Hibernate Criteria API提供了面向对象的方法来查询数据库和获取结果。 我们不能在Hibernate中使用Criteria来运行更新或删除查询或任何DDL语句。 Hibernate Criteria查询仅用于使用面向对象方法从数据库中获取结果。

For my Hibernate criteria example, I will use the same setup as in my HQL Example and show you how to use Criteria in Hibernate for querying databases.

对于我的Hibernate标准示例,我将使用与HQL示例相同的设置,并向您展示如何在Hibernate中使用Criteria来查询数据库。

Some of the common usage of Hibernate Criteria API are;

Hibernate Criteria API的一些常见用法是:

  1. Hibernate Criteria API provides Projection that we can use for aggregate functions such as sum(), min(), max() etc.Hibernate Criteria API提供了Projection,我们可以将其用于聚合函数,例如sum(),min(),max()等。
  2. Hibernate Criteria API can be used with ProjectionList to fetch selected columns only.Hibernate Criteria API可以与ProjectionList一起使用,以仅获取选定的列。
  3. Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection()Hibernate中的条件可以通过连接多个表来用于连接查询,Hibernate条件中连接的有用方法是createAlias(),setFetchMode()和setProjection()
  4. Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.Hibernate API中的条件可用于获取有条件的结果,有用的方法是add(),我们可以在其中添加限制。
  5. Hibernate Criteria API provides addOrder() method that we can use for ordering the results.Hibernate Criteria API提供了addOrder()方法,可用于对结果进行排序。

Below class shows different usages of Hibernate Criteria API, most of these are replacements of examples in HQL tutorial.

下面的类展示了Hibernate Criteria API的不同用法,其中大多数是HQL教程中示例的替代。

package com.journaldev.hibernate.main;import java.util.Arrays;
import java.util.List;import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;import com.journaldev.hibernate.model.Employee;
import com.journaldev.hibernate.util.HibernateUtil;public class HibernateCriteriaExamples {@SuppressWarnings("unchecked")public static void main(String[] args) {// Prep workSessionFactory sessionFactory = HibernateUtil.getSessionFactory();Session session = sessionFactory.getCurrentSession();Transaction tx = session.beginTransaction();//Get All EmployeesCriteria criteria = session.createCriteria(Employee.class);List<Employee> empList = criteria.list();for(Employee emp : empList){System.out.println("ID="+emp.getId()+", Zipcode="+emp.getAddress().getZipcode());}// Get with ID, creating new Criteria to remove all the settingscriteria = session.createCriteria(Employee.class).add(Restrictions.eq("id", new Long(3)));Employee emp = (Employee) criteria.uniqueResult();System.out.println("Name=" + emp.getName() + ", City="+ emp.getAddress().getCity());//Pagination ExampleempList = session.createCriteria(Employee.class).addOrder(Order.desc("id")).setFirstResult(0).setMaxResults(2).list();for(Employee emp4 : empList){System.out.println("Paginated Employees::"+emp4.getId()+","+emp4.getAddress().getCity());}//Like exampleempList = session.createCriteria(Employee.class).add(Restrictions.like("name", "%i%")).list();for(Employee emp4 : empList){System.out.println("Employees having 'i' in name::"+emp4.getName()+","+emp4.getAddress().getCity());}//Projections examplelong count = (Long) session.createCriteria(Employee.class).setProjection(Projections.rowCount()).add(Restrictions.like("name", "%i%")).uniqueResult();System.out.println("Number of employees with 'i' in name="+count);//using Projections for sum, min, max aggregation functionsdouble sumSalary = (Double) session.createCriteria(Employee.class).setProjection(Projections.sum("salary")).uniqueResult();System.out.println("Sum of Salaries="+sumSalary);//Join example for selecting few columnscriteria = session.createCriteria(Employee.class, "employee");criteria.setFetchMode("employee.address", FetchMode.JOIN);criteria.createAlias("employee.address", "address"); // inner join by defaultProjectionList columns = Projections.projectionList().add(Projections.property("name")).add(Projections.property("address.city"));criteria.setProjection(columns);List<Object[]> list = criteria.list();for(Object[] arr : list){System.out.println(Arrays.toString(arr));}// Rollback transaction to avoid messing test datatx.commit();// closing hibernate resourcessessionFactory.close();}}

When we execute above Hibernate Criteria example program, we get following output.

当我们执行上面的Hibernate Criteria示例程序时,我们得到以下输出。

May 26, 2014 6:53:32 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
May 26, 2014 6:53:32 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
May 26, 2014 6:53:32 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 26, 2014 6:53:32 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 26, 2014 6:53:32 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: hibernate.cfg.xml
May 26, 2014 6:53:32 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: hibernate.cfg.xml
May 26, 2014 6:53:32 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace https://hibernate.sourceforge.net/. Use namespace https://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
May 26, 2014 6:53:32 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Hibernate Configuration loaded
Hibernate serviceRegistry created
May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/TestDB]
May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=pankaj, password=****}
May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
May 26, 2014 6:53:32 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
May 26, 2014 6:53:32 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
May 26, 2014 6:53:32 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select this_.emp_id as emp_id1_1_1_, this_.emp_name as emp_name2_1_1_, this_.emp_salary as emp_sala3_1_1_, address2_.emp_id as emp_id1_0_0_, address2_.address_line1 as address_2_0_0_, address2_.city as city3_0_0_, address2_.zipcode as zipcode4_0_0_ from EMPLOYEE this_ left outer join ADDRESS address2_ on this_.emp_id=address2_.emp_id
ID=1, Zipcode=95129
ID=2, Zipcode=95051
ID=3, Zipcode=560100
ID=4, Zipcode=100100
Hibernate: select this_.emp_id as emp_id1_1_1_, this_.emp_name as emp_name2_1_1_, this_.emp_salary as emp_sala3_1_1_, address2_.emp_id as emp_id1_0_0_, address2_.address_line1 as address_2_0_0_, address2_.city as city3_0_0_, address2_.zipcode as zipcode4_0_0_ from EMPLOYEE this_ left outer join ADDRESS address2_ on this_.emp_id=address2_.emp_id where this_.emp_id=?
Name=Lisa, City=Bangalore
Hibernate: select this_.emp_id as emp_id1_1_1_, this_.emp_name as emp_name2_1_1_, this_.emp_salary as emp_sala3_1_1_, address2_.emp_id as emp_id1_0_0_, address2_.address_line1 as address_2_0_0_, address2_.city as city3_0_0_, address2_.zipcode as zipcode4_0_0_ from EMPLOYEE this_ left outer join ADDRESS address2_ on this_.emp_id=address2_.emp_id order by this_.emp_id desc limit ?
Paginated Employees::4,New Delhi
Paginated Employees::3,Bangalore
Hibernate: select this_.emp_id as emp_id1_1_1_, this_.emp_name as emp_name2_1_1_, this_.emp_salary as emp_sala3_1_1_, address2_.emp_id as emp_id1_0_0_, address2_.address_line1 as address_2_0_0_, address2_.city as city3_0_0_, address2_.zipcode as zipcode4_0_0_ from EMPLOYEE this_ left outer join ADDRESS address2_ on this_.emp_id=address2_.emp_id where this_.emp_name like ?
Employees having 'i' in name::David,Santa Clara
Employees having 'i' in name::Lisa,Bangalore
Hibernate: select count(*) as y0_ from EMPLOYEE this_ where this_.emp_name like ?
Number of employees with 'i' in name=2
Hibernate: select sum(this_.emp_salary) as y0_ from EMPLOYEE this_
Sum of Salaries=1000.0
Hibernate: select this_.emp_name as y0_, address1_.city as y1_ from EMPLOYEE this_ inner join ADDRESS address1_ on this_.emp_id=address1_.emp_id
[Pankaj, San Jose]
[David, Santa Clara]
[Lisa, Bangalore]
[Jack, New Delhi]
May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost/TestDB]

Since I am using HQL example project, you would need to import that and then add this class for it to be working.

由于我使用的是HQL示例项目,因此您需要将其导入,然后添加此类以使其正常工作。

Notice the hibernate queries executed in the output, this way you can refine your queries and get the results you are looking for. That’s all for a quick roundup on Criteria in Hibernate.

注意输出中执行的Hibernate查询,这样您可以优化查询并获得所需的结果。 这就是Hibernate中Criteria的快速总结。

翻译自: https://www.journaldev.com/2963/hibernate-criteria-example-tutorial

hibernate示例

hibernate示例_Hibernate条件示例教程相关推荐

  1. Spring MVC Hibernate MySQL集成CRUD示例教程

    Spring MVC Hibernate MySQL集成CRUD示例教程 我们在上一篇教程中学习了如何集成Spring和Hibernate.今天,我们将继续前进,并将Spring MVC和Hibern ...

  2. Primefaces,Spring 4 with JPA(Hibernate 4 / EclipseLink)示例教程

    Primefaces,Spring 4 with JPA(Hibernate 4 / EclipseLink)示例教程 Java Persistence API是标准规范.它提供了一个由不同实现者框架 ...

  3. Hibernate Tomcat JNDI DataSource示例教程

    Hibernate Tomcat JNDI DataSource示例教程 欢迎来到Hibernate Tomcat JNDI DataSource示例教程.我们已经看到如何在独立的Java应用程序中使 ...

  4. Hibernate Tomcat JNDI数据源示例教程

    Welcome to the Hibernate Tomcat JNDI DataSource example tutorial. We have already seen how to use Hi ...

  5. hibernate示例_通过示例Hibernate–第1部分(删除孤儿)

    hibernate示例 所以我想做一系列的冬眠例子,展示冬眠的各种特征. 在第一部分中,我想展示有关删除孤儿功能及其在故事情节中的使用方式. 因此,让我们开始:) 先决条件 : 为了尝试以下示例,您将 ...

  6. Hibernate Native SQL查询示例

    Hibernate Native SQL查询示例 欢迎使用Hibernate Native SQL Query示例教程.我们在前面的文章中研究了Hibernate查询语言和Hibernate Crit ...

  7. linux条件表达式例子,Linux的Iptables命令的基本知识(三)-常用匹配条件示例和执行动作...

    上一期给大家简单讲解了Linux的Iptables命令的常用命令示例,本期给大家讲解一下Linux的Iptables命令的基本知识-常用匹配条件示例和执行动作. 五.常用匹配条件示例: 1.-i:流出 ...

  8. 淘宝,tmall,1688,抖音,拼多多等平台商品详情接口(网络爬虫数据接口调用示例)接口对接教程

    淘宝,tmall,1688,抖音,拼多多等平台商品详情接口(网络爬虫数据接口调用示例)接口对接教程如下: 1.公共参数 名称 类型 必须 描述(接口代码教程wx19970108018) key Str ...

  9. android jni示例_Android CollapsingToolbarLayout示例

    android jni示例 Welcome to Android CollapsingToolbarLayout Example. In this tutorial, we'll discuss an ...

最新文章

  1. 如何迅速成为Java高手[Tomjava原创]
  2. python读文件路径-python获取程序执行文件路径的方法(推荐)
  3. python类型转换-马哥教育官网-专业Linux培训班,Python培训机构
  4. ios视图frame和bounds的对比
  5. 开发---推荐16个国外的源码下载网站
  6. 弹性架构_实践中的弹性基础架构
  7. IOS7.1.1真的像网上流传的那么好?没有任何问题么??
  8. 测试电脑电源是否正常的办法
  9. php socket 读网页,PHP webSocket实现网页
  10. [XJTUSE编译原理]第四章 语法分析——自上而下分析
  11. GD32芯片包下载和安装教程
  12. 网吧游戏服务器制作教程,网吧服务器系统环境部署
  13. 单片机A/D采样的原理
  14. IP地址的定义与分类
  15. 书单|互联网企业面试案头书之运营篇
  16. 计算机知识与技能竞赛配图,第七届”高教杯“全国大学生先进成图技术与产品信息建模创新大赛机械类计算机绘图试卷.doc...
  17. 概率论与数理统计---随机变量的分布
  18. 2022年中级网络工程师备考(非网络知识部分)
  19. 美杜莎扫描器使用教程
  20. Word中10以内的都是带圆圈的数字到了11就没有圆圈

热门文章

  1. pthread_key_t和pthread_key_create()详解
  2. 对项目的总结以及对这种教学方式的看法
  3. elasticsearch集群搭建实例
  4. byte[]与Image Image与 byte[] 之间的转换
  5. [转载] python之flask框架
  6. [转载] python实现一个简易的计算器
  7. Ubuntu中使用pip3报错
  8. 微信小程序之 ----API接口
  9. ubuntu环境下,ubuntu16.04装机到nvdia显卡驱动安装、cuda8安装、cudnn安装
  10. Linux CentOS 中安装 MySql