Hibernate 标准示例教程

欢迎使用Hibernate标准示例教程。今天,我们将探讨Hibernate中的标准。

休眠条件

Criteria in Hibernate,Hibernate Criteria Example,Hibernate Criteria,Hibernate Criteria Join,Hibernate Criteria query大多数时候,我们使用hql来查询数据库并获得结果。HQL不是更新或删除值的首选方式,因为这样我们就需要处理表之间的任何关联。Hibernate Criteria API为查询数据库和获取结果提供了面向对象的方法。我们不能在Hibernate中使用条件来运行UPDATE或DELETE查询或任何DDL语句。Hibernate标准查询只用于使用面向对象的方法从数据库中获取结果。对于我的Hibernate标准示例,我将使用与我的HQL Example中相同的设置,并向您展示如何在Hibernate中使用条件来查询数据库。Hibernate Criteria API的一些常见用法包括;

1.Hibernate Criteria API提供了可用于聚合函数的投影,如sum()、min()、max()等。 2.Hibernate Criteria API只能与ProjectionList配合使用,只能拉取选中的列。 3.Hibernate中的条件可以用于连接多个表的连接查询,Hibernate条件连接的有用方法有createAlias()、setFetchModel()和setProjection() 4.Hibernate API中的条件可以用于带条件的结果获取,有用的方法是Add(),我们可以在其中添加限制。 5.Hibernate Criteria API提供了addOrder()方法,我们可以使用该方法对结果进行排序。

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

 1package com.journaldev.hibernate.main;
 2
 3import java.util.Arrays;
 4import java.util.List;
 5
 6import org.hibernate.Criteria;
 7import org.hibernate.FetchMode;
 8import org.hibernate.Session;
 9import org.hibernate.SessionFactory;
10import org.hibernate.Transaction;
11import org.hibernate.criterion.Order;
12import org.hibernate.criterion.ProjectionList;
13import org.hibernate.criterion.Projections;
14import org.hibernate.criterion.Restrictions;
15
16import com.journaldev.hibernate.model.Employee;
17import com.journaldev.hibernate.util.HibernateUtil;
18
19public class HibernateCriteriaExamples {
20
21    @SuppressWarnings("unchecked")
22    public static void main(String[] args) {
23    	// Prep work
24    	SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
25    	Session session = sessionFactory.getCurrentSession();
26    	Transaction tx = session.beginTransaction();
27
28    	//Get All Employees
29    	Criteria criteria = session.createCriteria(Employee.class);
30    	List<Employee> empList = criteria.list();
31    	for(Employee emp : empList){
32    		System.out.println("ID="+emp.getId()+", Zipcode="+emp.getAddress().getZipcode());
33    	}
34    	
35    	// Get with ID, creating new Criteria to remove all the settings
36    	criteria = session.createCriteria(Employee.class)
37    				.add(Restrictions.eq("id", new Long(3)));
38    	Employee emp = (Employee) criteria.uniqueResult();
39    	System.out.println("Name=" + emp.getName() + ", City="
40    			+ emp.getAddress().getCity());
41
42    	//Pagination Example
43    	empList = session.createCriteria(Employee.class)
44    				.addOrder(Order.desc("id"))
45    				.setFirstResult(0)
46    				.setMaxResults(2)
47    				.list();
48    	for(Employee emp4 : empList){
49    		System.out.println("Paginated Employees::"+emp4.getId()+","+emp4.getAddress().getCity());
50    	}
51
52    	//Like example
53    	empList = session.createCriteria(Employee.class)
54    			.add(Restrictions.like("name", "%i%"))
55    			.list();
56    	for(Employee emp4 : empList){
57    		System.out.println("Employees having 'i' in name::"+emp4.getName()+","+emp4.getAddress().getCity());
58    	}
59    	
60    	//Projections example
61    	long count = (Long) session.createCriteria(Employee.class)
62    			.setProjection(Projections.rowCount())
63    			.add(Restrictions.like("name", "%i%"))
64    			.uniqueResult();
65    	System.out.println("Number of employees with 'i' in name="+count);
66
67    	//using Projections for sum, min, max aggregation functions
68    	double sumSalary = (Double) session.createCriteria(Employee.class)
69    		.setProjection(Projections.sum("salary"))
70    		.uniqueResult();
71    	System.out.println("Sum of Salaries="+sumSalary);
72    	
73    	//Join example for selecting few columns
74    	criteria = session.createCriteria(Employee.class, "employee");
75    	criteria.setFetchMode("employee.address", FetchMode.JOIN);
76    	criteria.createAlias("employee.address", "address"); // inner join by default
77
78    	ProjectionList columns = Projections.projectionList()
79    					.add(Projections.property("name"))
80    					.add(Projections.property("address.city"));
81    	criteria.setProjection(columns);
82
83    	List<Object[]> list = criteria.list();
84    	for(Object[] arr : list){
85    		System.out.println(Arrays.toString(arr));
86    	}
87    	
88    	
89    	// Rollback transaction to avoid messing test data
90    	tx.commit();
91    	// closing hibernate resources
92    	sessionFactory.close();
93    }
94
95}

当我们执行上面的休眠标准示例程序时,我们会得到以下输出。

 1May 26, 2014 6:53:32 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
 2INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
 3May 26, 2014 6:53:32 PM org.hibernate.Version logVersion
 4INFO: HHH000412: Hibernate Core {4.3.5.Final}
 5May 26, 2014 6:53:32 PM org.hibernate.cfg.Environment <clinit>
 6INFO: HHH000206: hibernate.properties not found
 7May 26, 2014 6:53:32 PM org.hibernate.cfg.Environment buildBytecodeProvider
 8INFO: HHH000021: Bytecode provider name : javassist
 9May 26, 2014 6:53:32 PM org.hibernate.cfg.Configuration configure
10INFO: HHH000043: Configuring from resource: hibernate.cfg.xml
11May 26, 2014 6:53:32 PM org.hibernate.cfg.Configuration getConfigurationInputStream
12INFO: HHH000040: Configuration resource: hibernate.cfg.xml
13May 26, 2014 6:53:32 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
14WARN: HHH000223: Recognized obsolete hibernate namespace https://hibernate.sourceforge.net/. Use namespace https://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
15May 26, 2014 6:53:32 PM org.hibernate.cfg.Configuration doConfigure
16INFO: HHH000041: Configured SessionFactory: null
17Hibernate Configuration loaded
18Hibernate serviceRegistry created
19May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
20WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
21May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
22INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/TestDB]
23May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
24INFO: HHH000046: Connection properties: {user=pankaj, password=****}
25May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
26INFO: HHH000006: Autocommit mode: false
27May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
28INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
29May 26, 2014 6:53:32 PM org.hibernate.dialect.Dialect <init>
30INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
31May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
32INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
33May 26, 2014 6:53:32 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
34INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
35May 26, 2014 6:53:32 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
36INFO: HHH000397: Using ASTQueryTranslatorFactory
37Hibernate: 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
38ID=1, Zipcode=95129
39ID=2, Zipcode=95051
40ID=3, Zipcode=560100
41ID=4, Zipcode=100100
42Hibernate: 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=?
43Name=Lisa, City=Bangalore
44Hibernate: 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 ?
45Paginated Employees::4,New Delhi
46Paginated Employees::3,Bangalore
47Hibernate: 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 ?
48Employees having 'i' in name::David,Santa Clara
49Employees having 'i' in name::Lisa,Bangalore
50Hibernate: select count(*) as y0_ from EMPLOYEE this_ where this_.emp_name like ?
51Number of employees with 'i' in name=2
52Hibernate: select sum(this_.emp_salary) as y0_ from EMPLOYEE this_
53Sum of Salaries=1000.0
54Hibernate: select this_.emp_name as y0_, address1_.city as y1_ from EMPLOYEE this_ inner join ADDRESS address1_ on this_.emp_id=address1_.emp_id
55[Pankaj, San Jose]
56[David, Santa Clara]
57[Lisa, Bangalore]
58[Jack, New Delhi]
59May 26, 2014 6:53:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
60INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost/TestDB]

由于我使用的是HQL示例项目,因此您需要导入该项目,然后添加此类才能使其工作。请注意输出中执行的hibernate查询,这样您就可以细化查询并获得所需的结果。以上就是对Hibernate中的Criteria的快速总结。

Published At
Categories with 技术
Tagged with
comments powered by Disqus