关于HQL查询,我们可以结合hibernate的API文档,重点围绕org.hibernate.Query接口,分析其方法,此接口的实例对象是通过通过session、对象的creatQuery(String hql)方法得到的。我这里要分析HQL的select子句,当然要想深入HQL查询,我们就必须了解hibernate缓存的知识。
一、选择——Select子句查询返回对象的讨论
为什么只说Select子句,因为我们使用的hibernate框架是基于java语言环境下进行开发的,也就是说hibernate是将数据库进行了对象化,那么我们使用Select语句查询到的记录,返回的是什么对象,这个很让人感兴趣。
首先我们看看在只是用from子句的情况:
package com.third;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.third.Dao2.Students2;
public class Test3 {
private static SessionFactory sessionFactory;
private static Session session;
private static Transaction transaction;
@Before
public void init(){
//先获取配置对象,匹配hibernate.cfg.xml文件
Configuration config=new Configuration().configure();
//获取注册服务对象(该对象中包含hibernate.cfg.xml中的<properties>和<maping>信息
ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//获取sessionFactory对象,通过sessionFactory对象读取hibernate.cfg.xml文档信息,并通过<mapping>标签加载hbm.xml文件信息
sessionFactory=config.buildSessionFactory(serviceRegistry);
}
@Test
public void test3(){
//通过sessionFactory对象获取session对象
session=sessionFactory.openSession();
//通过session对象开启事务,并且返回事务(transaction)对象
transaction=session.beginTransaction();
//创建HQL语句用于后面的查询需要,需要查询Students2类
String hql="from Students2";
Query query=session.createQuery(hql);
List<Students2> students=query.list();
for (Students2 students2 : students) {
System.out.println("学号:"+students2.getSid()
+" 姓别:"+students2.getSgender()+" 姓名:"+students2.getSname());
}
}
@After
public void destory(){
transaction.commit();
//关闭开启的资源
if(session!=null){
session.close();
}
if(sessionFactory!=null){
sessionFactory.close();
}
}
我们能够看到上述代码中绿色背景的代码,说明查询对象query通过list()方法返回查询对象query的查询结果返回的是一个list集合且其泛型是Students2,也就是说只是用from子句查询返回的对象可以用Students类对象的集合接收,这个很好理解,你查的是Students2类在session中的所有实例对象的所有信息(这些对象和数据库中的students2表格记录一一对应),这个很合理。但是,如果我们使用Select语句,我们查询的Students2类在session中的实例对象的部分信息,那么返回的是什么对象?很显然,肯定不再是返回Students2类的对象。
我们看看下面的代码:用select语句挑选students2类的部分属性查询,强行用Students2对象接收返回的结果~
package com.third;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.third.Dao2.Students2;
public class Test3 {
private static SessionFactory sessionFactory;
private static Session session;
private static Transaction transaction;
@Before
public void init(){
//先获取配置对象,匹配hibernate.cfg.xml文件
Configuration config=new Configuration().configure();
//获取注册服务对象(该对象中包含hibernate.cfg.xml中的<properties>和<maping>信息
ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//获取sessionFactory对象,通过sessionFactory对象读取hibernate.cfg.xml文档信息,并通过<mapping>标签加载hbm.xml文件信息
sessionFactory=config.buildSessionFactory(serviceRegistry);
}
@Test
public void test3(){
//通过sessionFactory对象获取session对象
session=sessionFactory.openSession();
//通过session对象开启事务,并且返回事务(transaction)对象
transaction=session.beginTransaction();
//创建HQL语句用于后面的查询需要
//查询单条记录的sid和sname信息(hql语句)
String hql="select sid,sname,sgender from Students2 where sid=1";//创建单挑记录查询对象query
Query query=session.createQuery(hql);
54 List<Students2> list=query.list();
for (Students2 students2 : list) {
System.out.println("学号:"+students2.getSid()+" 姓名:"+students2.getSname());
}
}
@After
public void destory(){
transaction.commit();
//关闭开启的资源
if(session!=null){
session.close();
}
if(sessionFactory!=null){
sessionFactory.close();
}
}
}
运行代码之后:junit运行不通过,抛出异常:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.third.Dao2.Students2
at com.third.Test3.test3(Test3.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
我们重点看被我用绿色背景加重的错误报文,
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.third.Dao2.Students2 at com.third.Test3.test3(Test3.java:54)
大概意思是:程序在Test3.java的54行执行出现错误,即List<Students2> list=query.list();这行代码执行不了了,出现的错误是:java.lang.Object[]类对象没法映射到com.third.Dao2.Students2类对象中。
分析原因:
很明显通过query.list()方法返回的对象是Object[]类型单个个体或者集合,也就是说将数据库表格的每条记录的每个字段信息映以Object类对象的形式返回,而每条记录就是以一个Object[]类(Object类对象数组)对象返回,所有记录被封装在一个list集合中。也就是说使用select子句的HQL查询语句,查询表格记录返回的对象类型是Object[]。
二、没有select子句的from子句查询对象讨论
之前我们说过只有from子句,查询表格记录返回的对象可以用查询类(Students类)对象的集合接收,并没有指出到底返回的对象是什么类型。然后我们开始思考没有select子句,只有from子句的查询,查询表格记录返回的对象类型到底是什么?
我们开始尝试使用List<Object[]> list=query.list();即使用Object[]来接受只有from子句的HQL查询表格记录返回的对象:
1 package com.third;
2
3 import java.util.List;
4
5 import org.hibernate.Query;
6 import org.hibernate.Session;
7 import org.hibernate.SessionFactory;
8 import org.hibernate.Transaction;
9 import org.hibernate.cfg.Configuration;
10 import org.hibernate.service.ServiceRegistry;
11 import org.hibernate.service.ServiceRegistryBuilder;
12 import org.junit.After;
13 import org.junit.Before;
14 import org.junit.Test;
15
16 import com.third.Dao2.Students2;
17
18 public class Test3 {
19 private static SessionFactory sessionFactory;
20 private static Session session;
21 private static Transaction transaction;
22 @Before
23 public void init(){
24 //先获取配置对象,匹配hibernate.cfg.xml文件
25 Configuration config=new Configuration().configure();
26 //获取注册服务对象(该对象中包含hibernate.cfg.xml中的<properties>和<maping>信息
27 ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
28 //获取sessionFactory对象,通过sessionFactory对象读取hibernate.cfg.xml文档信息,并通过<mapping>标签加载hbm.xml文件信息
29 sessionFactory=config.buildSessionFactory(serviceRegistry);
30 }
31
32 @Test
33 public void test3(){
34 //通过sessionFactory对象获取session对象
35 session=sessionFactory.openSession();
36 //通过session对象开启事务,并且返回事务(transaction)对象
37 transaction=session.beginTransaction();
38
39 //创建HQL语句用于后面的查询需要
40 //查询所有记录的sid和sname信息(hql语句)
41 String hql=" from Students2";
42
43 //创建多条记录查询对象query1
44 Query query=session.createQuery(hql);
45
46 List<Object[]> list=query.list();
47 for (Object[] objects : list) {
48 System.out.println("学号:"+objects[0]+" 姓名:"+objects[1]+" 性别:"+objects[2]);
49 }
50
51 }
52
53 @After
54 public void destory(){
55 transaction.commit();
56 //关闭开启的资源
57 if(session!=null){
58 session.close();
59 }
60 if(sessionFactory!=null){
61 sessionFactory.close();
62 }
63 }
64 }
使用junit调试后,抛出异常:
java.lang.ClassCastException: com.third.Dao2.Students2 cannot be cast to [Ljava.lang.Object;
at com.third.Test3.test3(Test3.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
我们重点分析绿色背景的错误报文
java.lang.ClassCastException: com.third.Dao2.Students2 cannot be cast to [Ljava.lang.Object; at com.third.Test3.test3(Test3.java:46)
大概意思是:程序在Test3.java的46行执行出现错误,即List<Object[]> list=query.list();这行代码执行不了了,出现的错误是:com.third.Dao2.Students2类对象没法映射到java.lang.Object[]类对象中。
这个就很戏剧化了,正好和使用select子句的情况相反。这就说明只有from子句的HQL查询,查询表格记录返回的对象是查询类对象(com.third.Dao2.Students2类对象)。
三、给出几种正确的select查询处理方法:
1、以Object[]形式返回
select子句中未指定返回数据类型,默认为Object[].
代码示例:
1 package com.third;
2
3 import java.util.Iterator;
4 import java.util.List;
5
6 import org.hibernate.Query;
7 import org.hibernate.ScrollableResults;
8 import org.hibernate.Session;
9 import org.hibernate.SessionFactory;
10 import org.hibernate.Transaction;
11 import org.hibernate.cfg.Configuration;
12 import org.hibernate.service.ServiceRegistry;
13 import org.hibernate.service.ServiceRegistryBuilder;
14 import org.junit.After;
15 import org.junit.Before;
16 import org.junit.Test;
17
18 import com.third.Dao2.Students2;
19
20 public class Test3 {
21 private static SessionFactory sessionFactory;
22 private static Session session;
23 private static Transaction transaction;
24 @Before
25 public void init(){
26 //先获取配置对象,匹配hibernate.cfg.xml文件
27 Configuration config=new Configuration().configure();
28 //获取注册服务对象(该对象中包含hibernate.cfg.xml中的<properties>和<maping>信息
29 ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
30 //获取sessionFactory对象,通过sessionFactory对象读取hibernate.cfg.xml文档信息,并通过<mapping>标签加载hbm.xml文件信息
31 sessionFactory=config.buildSessionFactory(serviceRegistry);
32 }
33
34 @Test
35 public void test3(){
36 //通过sessionFactory对象获取session对象
37 session=sessionFactory.openSession();
38 //通过session对象开启事务,并且返回事务(transaction)对象
39 transaction=session.beginTransaction();
40
41 //创建HQL语句用于后面的查询需要
42 //查询所有记录的sid和sname信息(hql语句)
43 String hql1="select sid,sname from Students2 ";
44 //创建多条记录查询对象query1
45 Query query1=session.createQuery(hql1);
46
47 List<Object[]> list1=query1.list();
48 for (Object[] objects : list1) {
49 System.out.println("学号:"+objects[0]+" 姓名:"+objects[1]);
50 }
51
52 /*Iterator<Students2> it=query.iterate();
53 while(it.hasNext()){
54 Students2 stu=it.next();
55 System.out.println("学号:"+stu.getSid()
56 +" 姓别:"+stu.getSgender()+" 姓名:"+stu.getSname());
57 }*/
58
59 }
60
61 @After
62 public void destory(){
63 transaction.commit();
64 //关闭开启的资源
65 if(session!=null){
66 session.close();
67 }
68 if(sessionFactory!=null){
69 sessionFactory.close();
70 }
71 }
72 }
2、以List形式返回
select子句使用new List指定
1 package com.third;
2
3 import java.util.Iterator;
4 import java.util.List;
5
6 import org.hibernate.Query;
7 import org.hibernate.ScrollableResults;
8 import org.hibernate.Session;
9 import org.hibernate.SessionFactory;
10 import org.hibernate.Transaction;
11 import org.hibernate.cfg.Configuration;
12 import org.hibernate.service.ServiceRegistry;
13 import org.hibernate.service.ServiceRegistryBuilder;
14 import org.junit.After;
15 import org.junit.Before;
16 import org.junit.Test;
17
18 import com.third.Dao2.Students2;
19
20 public class Test3 {
21 private static SessionFactory sessionFactory;
22 private static Session session;
23 private static Transaction transaction;
24 @Before
25 public void init(){
26 //先获取配置对象,匹配hibernate.cfg.xml文件
27 Configuration config=new Configuration().configure();
28 //获取注册服务对象(该对象中包含hibernate.cfg.xml中的<properties>和<maping>信息
29 ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
30 //获取sessionFactory对象,通过sessionFactory对象读取hibernate.cfg.xml文档信息,并通过<mapping>标签加载hbm.xml文件信息
31 sessionFactory=config.buildSessionFactory(serviceRegistry);
32 }
33
34 @Test
35 public void test3(){
36 //通过sessionFactory对象获取session对象
37 session=sessionFactory.openSession();
38 //通过session对象开启事务,并且返回事务(transaction)对象
39 transaction=session.beginTransaction();
40
41 //创建HQL语句用于后面的查询需要
42 //查询所有记录的sid和sname信息(hql语句)
43 String hql1="select new list(sid,sname) from Students2 ";
44 //创建多条记录查询对象query1
45 Query query1=session.createQuery(hql1);
46
47 List<List> list1=query1.list();
48 for (List list : list1) {
49 System.out.println("学号:"+list.get(0)+" 姓名:"+list.get(1));
50 }
51
52 }
53
54 @After
55 public void destory(){
56 transaction.commit();
57 //关闭开启的资源
58 if(session!=null){
59 session.close();
60 }
61 if(sessionFactory!=null){
62 sessionFactory.close();
63 }
64 }
65 }
首先我们来分析其中的HQL语句select new list(sid,sname) from Students2 其中new list(sid,,sname)直接指定了查询返回的是list集合。如果我们在这里强行使用其他的对象类型来接受返回的对象,会出现什么?
我们可以看一下下面的情况(稍微修改了接收对象类型):
//查询所有记录的sid和sname信息(hql语句)
String hql1="select new list(sid,sname) from Students2 ";
//创建多条记录查询对象query1
Query query1=session.createQuery(hql1);
50 List<Object[]> list1=query1.list();
for (Object[] objects : list1) {
System.out.println("学号:"+objects[0]+" 姓名:"+objects[1]);
}
运行程序时抛出异常:
java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to [Ljava.lang.Object;
at com.third.Test3.test3(Test3.java:50)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
我们重点看这两句错误报文:
java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to [Ljava.lang.Object;
at com.third.Test3.test3(Test3.java:50)
程序在Test3.java的50行执行出现错误,即List<Obiect[]>
list=query.list();这行代码执行不了了,出现的错误是: java.util.Arrays$ArrayList类对象没法映射到java.lang.Object[]类对象中。
这里我们可以的到一个结论:HQL语句通过new list(...)方式查询,查询对象query通过list()方法返回的list集合内对象类型是java.util.Arrays$ArrayList,并且表格的记录最终的查询信息对象,只能使用list对象去接收。
3、以Map形式返回
select子句使用new map指定,这里特别要注意map是以键值对形式储存,所以其get()方法中势必可以存储属性名,我们可以通过get(string name)方法读取信息。所以读取查询结果时我们有两种方式。然后其他的内容和new list相似,不在过多赘述了。
代码示例:
1 package com.third;
2
3 import java.lang.reflect.Field;
4 import java.util.Iterator;
5 import java.util.List;
6 import java.util.Map;
7
8 import org.hibernate.Query;
9 import org.hibernate.ScrollableResults;
10 import org.hibernate.Session;
11 import org.hibernate.SessionFactory;
12 import org.hibernate.Transaction;
13 import org.hibernate.cfg.Configuration;
14 import org.hibernate.service.ServiceRegistry;
15 import org.hibernate.service.ServiceRegistryBuilder;
16 import org.junit.After;
17 import org.junit.Before;
18 import org.junit.Test;
19
20 import com.third.Dao2.Students2;
21
22 public class Test3 {
23 private static SessionFactory sessionFactory;
24 private static Session session;
25 private static Transaction transaction;
26 @Before
27 public void init(){
28 //先获取配置对象,匹配hibernate.cfg.xml文件
29 Configuration config=new Configuration().configure();
30 //获取注册服务对象(该对象中包含hibernate.cfg.xml中的<properties>和<maping>信息
31 ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
32 //获取sessionFactory对象,通过sessionFactory对象读取hibernate.cfg.xml文档信息,并通过<mapping>标签加载hbm.xml文件信息
33 sessionFactory=config.buildSessionFactory(serviceRegistry);
34 }
35
36 @Test
37 public void test3(){
38 //通过sessionFactory对象获取session对象
39 session=sessionFactory.openSession();
40 //通过session对象开启事务,并且返回事务(transaction)对象
41 transaction=session.beginTransaction();
42
43 //创建HQL语句用于后面的查询需要
44 //查询所有记录的sid和sname信息(hql语句)
45 String hql="select new map(sid ,sname) from Students2";
46 String hql1="select new map(sid as id,sname as name) from Students2 ";
47
48 //创建多条记录查询对象query1
49 Query query=session.createQuery(hql);
50 Query query1=session.createQuery(hql1);
51 List<Map> list=query.list();
52 List<Map> list1=query1.list();
53 for (Map map : list) {
54 System.out.println("学号:"+map.get("0")+" 姓名:"+map.get("1"));
55 }
56 System.out.println("*******************");
57 for (Map map : list1) {
58 System.out.println("学号:"+map.get("id")+" 姓名:"+map.get("name"));
59 }
60
61
62 }
63
64 @After
65 public void destory(){
66 transaction.commit();
67 //关闭开启的资源
68 if(session!=null){
69 session.close();
70 }
71 if(sessionFactory!=null){
72 sessionFactory.close();
73 }
74 }
75 }
4、以自定义类型返回
(1)持久化类中定义对应的构造器
(2)select子句中调用定义的构造器
首先我们需要要查询类(持久化类中添加相应的构造函数)
Students2.java
package com.third.Dao2;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class Students2 implements Serializable {
private int sid;
private String sname;
private String sgender;
private Set<Teachers> teaList=new HashSet<Teachers>();
public Students2(int sid, String sname) {
this.sid = sid;
this.sname = sname;
}
public Students2() {
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSgender() {
return sgender;
}
public void setSgender(String sgender) {
this.sgender = sgender;
}
public Set<Teachers> getTeaList() {
return teaList;
}
public void setTeaList(Set<Teachers> teaList) {
this.teaList = teaList;
}
}
1 package com.third;
2
3 import java.util.List;
4
5 import org.hibernate.Query;
6 import org.hibernate.Session;
7 import org.hibernate.SessionFactory;
8 import org.hibernate.Transaction;
9 import org.hibernate.cfg.Configuration;
10 import org.hibernate.service.ServiceRegistry;
11 import org.hibernate.service.ServiceRegistryBuilder;
12 import org.junit.After;
13 import org.junit.Before;
14 import org.junit.Test;
15
16 import com.third.Dao2.Students2;
17
18 public class Test3 {
19 private static SessionFactory sessionFactory;
20 private static Session session;
21 private static Transaction transaction;
22 @Before
23 public void init(){
24 //先获取配置对象,匹配hibernate.cfg.xml文件
25 Configuration config=new Configuration().configure();
26 //获取注册服务对象(该对象中包含hibernate.cfg.xml中的<properties>和<maping>信息
27 ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
28 //获取sessionFactory对象,通过sessionFactory对象读取hibernate.cfg.xml文档信息,并通过<mapping>标签加载hbm.xml文件信息
29 sessionFactory=config.buildSessionFactory(serviceRegistry);
30 }
31
32 @Test
33 public void test3(){
34 //通过sessionFactory对象获取session对象
35 session=sessionFactory.openSession();
36 //通过session对象开启事务,并且返回事务(transaction)对象
37 transaction=session.beginTransaction();
38
39 //创建HQL语句用于后面的查询需要
40 //查询所有记录的sid和sname信息(hql语句)
41 String hql="select new Students2(sid ,sname) from Students2";
42
43 //创建多条记录查询对象query1
44 Query query=session.createQuery(hql);
45
46 List<Students2> list=query.list();
47
48 for (Students2 stu : list) {
49 System.out.println("学号:"+stu.getSid()+" 姓名:"+stu.getSname());
50 }
59 }
60
61 @After
62 public void destory(){
63 transaction.commit();
64 //关闭开启的资源
65 if(session!=null){
66 session.close();
67 }
68 if(sessionFactory!=null){
69 sessionFactory.close();
70 }
71 }
72 }
其他的主要内容和new list方式一样。
四、总结:
1、没有select子句有from子句的HQL查询,查询表格的记录,返回的对象是查询类对象;即List<查询类名> list=query.list();
2、有select子句的HQL查询,查询表格记录,返回的对象是Object[]类对象,即List<Object[]> lsit=query.lsit();
3、我们可以通过在HQL语句中使用new list(...),new map(...),new Students2(...)的方式来指定查询返回的对象类型。
4、使用new Students2(...)的方式,即以自定义类型返回的方式,需要在该查询类的持久化类Students2.java中添加相应的构造函数。