问题描述
有时候我回问了有关如何使用Hibernate进行Distinct查询的问题。现在,我已经超越了这个里程碑,我还需要另一件事。就是说,给定表格
Sometime back I asked the question regarding how to do a Distinct query using Hibernate. Now that I'm past that milestone, there is another thing that I require. And that is, given the table,
---------------------------------------
| user_id | user_name | user_type |
---------------------------------------
| 1 | mark taylor | admin |
| 2 | bill paxton |co-ordinator|
| 1 | tony brooks | admin |
| 3 | ali jahan | developer |
---------------------------------------
我想创建一个不同的查询,该查询返回不同的user_type及其对应的user_id。 请注意,特定user_type的user_id相同。因此,例如,
I want to create a distinct query which returns the distinct user_type along with it's corresponding user_id. Please do note that the user_id for a particular user_type is same. So for example,
admin = 1
co-ordinator = 2
developer = 3
所以我期望的回报有点像ArrayList或包含两个值的排序
So the return I'm expecting is somewhat like a ArrayList or that sort which contains both values like
user_id,user_type
我为获得Distinct UserType编写的代码如下,我希望可以对其进行一些修改以获得所需的结果。
The code I've written to get Distinct UserType is as follows and I'm hoping there could be some modification to it to get the desired result.
public List<String> findDistinctUserName() throws HibernateException {
List<String> returnVal = new ArrayList<String>();
Criteria c = this.createCriteria();
c.setProjection(Projections.distinct(Projections.property("userType")));
c.addOrder(Order.asc("userType"));
List<String> userTypeList = c.list();
for(String userType : userTypeList) {
if(!userType.equalsIgnoreCase("")) {
returnVal.add(userType);
}
}
return returnVal;
}
谢谢您的回答。
推荐答案
尝试一下:
条件。setProjection(Projections.distinct(Projections.property( userType))), userType);
Try this:
criteria.setProjection(Projections.distinct(Projections.property("userType")), "userType");
另外,您也不必检查空白字符串,请尝试以下操作:
Also u don't have to check for blank strings, try this:
criteria.add(限制.ne( userType,));
criteria.add(Restrictions.ne("userType",""));
这篇关于Hibernate-不同的查询返回两列结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!