在hibernate createSQlquery结果中使用sql列名 [英] Using sql column names in hibernate createSQlquery result

查看:426
本文介绍了在hibernate createSQlquery结果中使用sql列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些我想查询的具有复合主键的sql视图,而且由于Hibernate使用复合关键字很麻烦,我使用 createSQLQuery 。问题是这个方法只能返回一个List,我需要通过它们的索引来引用colums。



任何机会我都可以做类似jdbc的事情,并通过他们的sql名称而不是索引来引用列?

解决方案

 查询查询= session.createSQLQuery(您的查询); 
query.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List< Map< String,Object>> aliasToValueMapList = query.list();

从代码中可以看出,列表包含代表每行的Map对象。每个Map对象都有列名作为键和值作为值。注意:这项工作适用于SQLQuery,如果您在没有指定别名的情况下使用Hql查询上的AliasToEntityMapResultTransformer,您将获得索引值作为关键字。

如果您再次将aliasToValueMapList转换为您的POJO列表,我建议您创建自己的
ResultTransformer 并从'transformTuple'方法返回您的自定义对象。


I have a couple of sql views with composite primary keys that I want to query, and since Hibernate makes it a pain to work with composite keyes, I'm using createSQLQuery. The problem is that this method can only return a List, and I need to refer to the colums by their index.

Any chance I could do something like jdbc and refer to the columns by their sql name instead of their index?

解决方案

Query query=session.createSQLQuery("your query");
query.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List<Map<String,Object>> aliasToValueMapList=query.list();

As you can figure out from code, the list contains Map objects representing each row. Each Map object will have column name as key and value as value.

Note: This work for SQLQuery, if your using AliasToEntityMapResultTransformer on hql query without specifying aliases you will get index value as key.

If you are again transforming aliasToValueMapList to your POJO list, I advice you to create your own ResultTransformer and return your custom object from 'transformTuple' method.

这篇关于在hibernate createSQlquery结果中使用sql列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆