Select Distinct user_type from Users
users表的值如下,
---------------------------------------
| user_id | user_name | user_type |
---------------------------------------
| 1 | mark taylor | admin |
| 2 | bill paxton |co-ordinator|
| 3 | tony brooks | admin |
| 4 | ali jahan | developer |
---------------------------------------
我在查询结束时期待的结果是,
admin,co-ordinator,developer
我希望获得的是一个user_types列表作为return语句,我在搜索帮助后编写的函数如下,
public List<User> findDistinctUserType() throws HibernateException {
Criteria c = this.createCriteria();
c.setProjection(Projections.distinct(Projections.property("user_type")));
return (List<User>) (User) c.uniqueResult();
}
我看了另一个例子并尝试过这个,
public List<User> findDistinctUserType() throws HibernateException {
Criteria c = this.createCriteria();
ProjectionList projectionList = Projections.projectionList();
ProjectionList projectionList2 = Projections.projectionList();
projectionList2.add(Projections.distinct(projectionList
.add(Projections.property("user_type"),"user_type")));
c.setProjection(projectionList2);
c.setResultTransformer(Transformers.aliasToBean(User.class));
return (List<User>) (User) c.uniqueResult();
}
但是由于奇怪的原因,它总是失败而且我没有通过,如果你能为我提供一个很好的解决方案,那就太棒了。期待您的帮助。
提前致谢
修改
我期待的输出如下,
admin,co-ordinator,developer
我目前在没有此代码的情况下获得的是
admin,co-ordinator,admin,developer
以下列方式调用上述函数,
List<User> userList = userDao.findDistinctUserType();
用户是包含以下信息的对象
private int id;
private String userName;
private String userType;
进一步向下定义用户对象的代码,我们有,
@Column(name="user_type", nullable=false)
public String getUserType() {
return userType;
}
答案 0 :(得分:-1)
感谢大家的所有反馈,我能够解决问题。根据你的建议,我做了这个,这对我有用,
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;
}
感谢您的所有答案。准备好我可能会问更多,因为我一起去哈哈!