简体   繁体   English

Hibernate-不同的查询返回两列结果

[英]Hibernate - Distinct Query returning two columns result

Sometime back I asked the question regarding how to do a Distinct query using Hibernate. 有时我问过有关如何使用Hibernate进行Distinct查询的问题。 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  |
---------------------------------------

I want to create a distinct query which returns the distinct user_type along with it's corresponding user_id. 我想创建一个不同的查询,该查询返回不同的user_type及其对应的user_id。 Please do note that the user_id for a particular user_type is same . 请注意,特定user_type的user_id是相同的 So for example, 例如

admin = 1
co-ordinator = 2
developer = 3

So the return I'm expecting is somewhat like a ArrayList or that sort which contains both values like 所以我期望的回报有点像ArrayList或包含两个值的排序

user_id,user_type

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. 我编写的用于获取Distinct UserType的代码如下,我希望可以对其进行一些修改以获得所需的结果。

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;
}

Thank you for your answers in advance. 预先感谢您的回答。

Try this: 尝试这个:
criteria.setProjection(Projections.distinct(Projections.property("userType")), "userType"); 条件.setProjection(Projections.distinct(Projections.property(“ userType”)),“ userType”));

Also u don't have to check for blank strings, try this: 另外,您不必检查空白字符串,请尝试以下操作:

criteria.add(Restrictions.ne("userType","")); criteria.add(Restrictions.ne( “用户类型”, “”));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM