当我们用HQL进行子查询的时候,如select * from Tree where pid in (select id from Tree,此时HIBERANTE就会报错,说什么*号错误之类的。但如果将*改为Tree类里的所有子段时就不会有问题了。就会像平时一样第一行数据返回一个Object[],然后你再根据Tree类里字段对Object[]数组里的值进行转换。这样一来比较麻烦。今天发现如果我SQL来查有一个方法可以返回一个对象的。
Configuration config = new Configuration().configure();
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
Transaction ts = session.beginTransaction();
Query query = session.createSQLQuery("select * from Tree t where pid in (select id from Tree) ").addEntity(Tree.class); //返回对象
List list = query.list();
此时在遍历list时就可以(Tree)list.get[i];将每一行的内容变换为一个对象了。
另还可以返回一个Map对象,也就是说在在list里包含多个Map,代码如下
Query query = session.createSQLQuery("select id,name from Tree t where pid in (select id from Tree) ").setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); //返回一个map,KEY:为DB中名称一致(大小写一致)遍历list时就可以
Map map = (Map)list.get[i];
map.get("id");map.get("name");来取值。按你的SQL语句select后的字段名来作为map的Key,但这个key必须与数据库中的字段名一模一样。
还可以用作函数方面的。如
Query query = session.createSQLQuery("select sum(id) SUMID from Tree t where pid in (select id from Tree)
.addScalar("SUMID",Hibernate.INTEGER) //转换类型,按DB中的type转
.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); //返回一个map,KEY:为DB中名称一致(大小写一致)
直接就map.get("SUMID")可以取值了
分享到:
相关推荐
hibernate 的createSQLQuery的几种用法总结
关于hibernate 的createQuery和createSqlQuery 的区别
使用hibernate的query调用oracle的存储过程/function,包含例子,源码以及数据库文件
16.3.5 用带子查询的select语句整批量初始化orders集合(fetch属性为“subselect”) 16.3.6 迫切左外连接检索(fetch属性为“join”) 16.4 多对一和一对一关联的检索策略 16.4.1 迫切左外连接检索(fetch...
16.3.5 用带子查询的select语句整批量初始化orders集合(fetch属性为“subselect”) 16.3.6 迫切左外连接检索(fetch属性为“join”) 16.4 多对一和一对一关联的检索策略 16.4.1 迫切左外连接检索(fetch...
16.3.5 用带子查询的select语句整批量初始化orders集合(fetch属性为“subselect”) 16.3.6 迫切左外连接检索(fetch属性为“join”) 16.4 多对一和一对一关联的检索策略 16.4.1 迫切左外连接检索(fetch...
16.3.5 用带子查询的select语句整批量初始化orders集合(fetch属性为“subselect”) 16.3.6 迫切左外连接检索(fetch属性为“join”) 16.4 多对一和一对一关联的检索策略 16.4.1 迫切左外连接检索(fetch...
If Hiberate is used, with the help of query builder (createSQLQuery) in org.hibernate.Session, one can mention the placeholder parameter name in the SQL and set the values based on the parameter name....