博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hibernate示例_Hibernate条件示例教程
阅读量:2531 次
发布时间:2019-05-11

本文共 11109 字,大约阅读时间需要 37 分钟。

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 and show you how to use Criteria in Hibernate for querying databases.

对于我的Hibernate标准示例,我将使用与相同的设置,并向您展示如何在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 work		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();		Session session = sessionFactory.getCurrentSession();		Transaction tx = session.beginTransaction();		//Get All Employees		Criteria criteria = session.createCriteria(Employee.class);		List
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 settings criteria = 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 Example empList = 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 example empList = 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 example long 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 functions double sumSalary = (Double) session.createCriteria(Employee.class) .setProjection(Projections.sum("salary")) .uniqueResult(); System.out.println("Sum of Salaries="+sumSalary); //Join example for selecting few columns criteria = session.createCriteria(Employee.class, "employee"); criteria.setFetchMode("employee.address", FetchMode.JOIN); criteria.createAlias("employee.address", "address"); // inner join by default ProjectionList columns = Projections.projectionList() .add(Projections.property("name")) .add(Projections.property("address.city")); criteria.setProjection(columns); List
list = criteria.list(); for(Object[] arr : list){ System.out.println(Arrays.toString(arr)); } // Rollback transaction to avoid messing test data tx.commit(); // closing hibernate resources sessionFactory.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 
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}May 26, 2014 6:53:32 PM org.hibernate.Version logVersionINFO: HHH000412: Hibernate Core {4.3.5.Final}May 26, 2014 6:53:32 PM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not foundMay 26, 2014 6:53:32 PM org.hibernate.cfg.Environment buildBytecodeProviderINFO: HHH000021: Bytecode provider name : javassistMay 26, 2014 6:53:32 PM org.hibernate.cfg.Configuration configureINFO: HHH000043: Configuring from resource: hibernate.cfg.xmlMay 26, 2014 6:53:32 PM org.hibernate.cfg.Configuration getConfigurationInputStreamINFO: HHH000040: Configuration resource: hibernate.cfg.xmlMay 26, 2014 6:53:32 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntityWARN: 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 doConfigureINFO: HHH000041: Configured SessionFactory: nullHibernate Configuration loadedHibernate serviceRegistry createdMay 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configureWARN: 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 buildCreatorINFO: 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 buildCreatorINFO: HHH000046: Connection properties: {user=pankaj, password=****}May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreatorINFO: HHH000006: Autocommit mode: falseMay 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configureINFO: HHH000115: Hibernate connection pool size: 20 (min=1)May 26, 2014 6:53:32 PM org.hibernate.dialect.Dialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialectMay 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreationINFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4May 26, 2014 6:53:32 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateServiceINFO: HHH000399: Using default transaction strategy (direct JDBC transactions)May 26, 2014 6:53:32 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory
INFO: HHH000397: Using ASTQueryTranslatorFactoryHibernate: 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_idID=1, Zipcode=95129ID=2, Zipcode=95051ID=3, Zipcode=560100ID=4, Zipcode=100100Hibernate: 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=BangaloreHibernate: 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 DelhiPaginated Employees::3,BangaloreHibernate: 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 ClaraEmployees having 'i' in name::Lisa,BangaloreHibernate: select count(*) as y0_ from EMPLOYEE this_ where this_.emp_name like ?Number of employees with 'i' in name=2Hibernate: select sum(this_.emp_salary) as y0_ from EMPLOYEE this_Sum of Salaries=1000.0Hibernate: 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 stopINFO: 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的快速总结。

翻译自:

hibernate示例

转载地址:http://kjlzd.baihongyu.com/

你可能感兴趣的文章
i++和++1
查看>>
react.js
查看>>
P1313 计算系数
查看>>
NSString的长度比较方法(一)
查看>>
Azure云服务托管恶意软件
查看>>
My安卓知识6--关于把项目从androidstudio工程转成eclipse工程并导成jar包
查看>>
旧的起点(开园说明)
查看>>
生产订单“生产线别”带入生产入库单
查看>>
crontab导致磁盘空间满问题的解决
查看>>
java基础 第十一章(多态、抽象类、接口、包装类、String)
查看>>
Hadoop 服务器配置的副本数量 管不了客户端
查看>>
欧建新之死
查看>>
自定义滚动条
查看>>
APP开发手记01(app与web的困惑)
查看>>
笛卡尔遗传规划Cartesian Genetic Programming (CGP)简单理解(1)
查看>>
mysql 日期时间运算函数(转)
查看>>
初识前端作业1
查看>>
ffmpeg格式转换命令
查看>>
万方数据知识平台 TFHpple +Xpath解析
查看>>
Hive实现oracle的Minus函数
查看>>