在hibernate中查询使用list,map定制返回类型
来源:互联网 发布:广州java培训哪里好 编辑:程序博客网 时间:2024/06/08 14:51
在使用hibernate进行查询时,使用得最多的还是通过构建hql进行查询了。在查询的过程当中,除使用经常的查询对象方法之外,还会遇到查询一个属性,或一组聚集结果的情况。在这种情况下,我们通常就需要对返回的结构进行处理。
一般情况下,我们通过构建hql,并通过设置query的resultTransformer来定制返回结果的类型,一般设置为map属性,如下所示:
1
2
Query query = session.createQuery(
"hql"
);
query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
来指定查询结果的每一项为一个map。
不过,随着hibernate的发展,可以在hql中直接使用集合查询语句,如list和map了。以下分别介绍使用list和map时的查询语句以及查询结果。首先,数据库的数据如下所示:
1
2
3
4
5
6
7
8
9
mysql> select * from p_dictionary;
+-----------------+----+---------+------+--------+--------+
| dictionary_type | id | version | code | forbid | value |
+-----------------+----+---------+------+--------+--------+
| COUNTY | 1 | 0 | 001 | | 四川 |
| COUNTY | 2 | 0 | 002 | | 北京 |
| COUNTY | 3 | 0 | 001 | NULL | 四川 |
+-----------------+----+---------+------+--------+--------+
3 rows in set (0.00 sec)
以下分别介绍使用list和map的查询语句和查询结果:
使用list
1
2
3
4
5
String query =
"select new list(p.code,p.value) from Dictionary p"
;
List list = session.createQuery(query).list();
System.out.println(list);
//结果
[[
001
, 四川], [
002
, 北京], [
001
, 四川]]
使用map,首先不指定alias,则结果的键就按照查询出来的顺序结果,使用0,1来表示key
1
2
3
4
String query =
"select new map(p.code,p.value) from Dictionary p"
;
List list = session.createQuery(query).list();
//结果
[{
1
=四川,
0
=
001
}, {
1
=北京,
0
=
002
}, {
1
=四川,
0
=
001
}]
使用map,指定alias,则结果中的key则为alias
1
2
3
4
String query =
"select new map(p.code as code,p.value as value) from Dictionary p"
;
List list = session.createQuery(query).list();
//结果
[{value=四川, code=
001
}, {value=北京, code=
002
}, {value=四川, code=
001
}]
如果部分使用alias,部分不使用,则使用了alias的将使用alias作为key,没有使用的则仍然使用序号代替,其中序号则为在查询结果的序号
1
2
3
4
String query =
"select new map(p.code as code,p.value) from Dictionary p"
;
List list = session.createQuery(query).list();
//结果
[{
1
=四川, code=
001
}, {
1
=北京, code=
002
}, {
1
=四川, code=
001
}]
本文地址:http://www.iflym.com/index.php/code/use-list-set-map-in-hibernate-query.html
- 在hibernate中查询使用list,map定制返回类型
- 在hibernate中查询使用list,map定制返回类型
- 在hibernate中查询使用List,Map和类对象定制返回类型
- 在hibernate中查询使用List,Map和类对象定制返回类型
- 在hibernate中查询使用List,Map和类对象定制返回类型
- hql查询返回list,map,自定义类型
- hibernate 返回List<Map>, List<xxx>对象列表类型
- hibernate下使用getHibernateTemplate 返回List<Map>
- Hibernate使用SQLQuery返回List<Map>
- mybatis查询如何返回List<Map>类型数据
- mybatis查询如何返回List<Map>类型数据
- hibernate查询返回List
- Hibernate使用SQL查询返回实体类型
- Hibernate使用SQL查询返回实体类型
- Hibernate使用SQL查询返回实体类型
- Hibernate 多表关联映射- Hibernate中使用的集合类型(set,list,array,bag,map)
- 服务器返回的list,map等类型,在JSP中取长度、取值的方法
- HQL 定制返回类型map ALIAS_TO_ENTITY_MAP
- oracle 集合 API
- C# vs Java:北乔峰 vs 南慕容
- [C# 网络编程系列]专题十:实现简单的邮件收发器
- exited abnormally with signal 11: Segmentation fault 的相关处理
- 76555784368578
- 在hibernate中查询使用list,map定制返回类型
- zen coding for sublime text2
- 路由器的一个端口(ip1~ip2)下的所有终端(在没有路由器的情况下)构成一个局域网?
- MyEclipse Could not create the view: An unexpected exception was thrown. 错误
- 最近的一些感悟
- POJ 1252
- take it easy II
- 76555784368578
- 哈夫曼树