java hibernate标准投影rowCount只有1列

时间:2013-04-20 22:54:00

标签: java hibernate criteria projection

我有一个hibernate查询来检查学生的别名(user_name)是唯一的,这是非常好的,这是我的代码。

public Boolean isAliasUniqueInStudent(String alias) 
{        
    Session session = getHibernateTemplate().getSessionFactory().openSession();        
    ProjectionList p = Projections.projectionList().add(Projections.rowCount());
    org.hibernate.criterion.Conjunction exist=(Conjunction)Restrictions.conjunction().add(Restrictions.isNotNull("username")).add(Restrictions.eq("username",alias));
    Criteria criteria = session().createCriteria(Student.class).setProjection(p).add(exist);               
    Long result=(Long)criteria.uniqueResult();
    closeSession(session);
    return result.intValue()==0;
}

这是创建这样的选择。

select count(*) as y0_ from student this_ where (this_.username is not null and this_.username=?)

这是非常好的,但我想知道是否可以尝试选择

select count(username) as y0_ from student this_ where (this_.username is not null and this_.username=?)

这比我的方法更好吗?

存在更好的一个吗?

我知道我正在检查属性不是null ..但这可能是用hibernate做的。

select count(name)

非常感谢。

1 个答案:

答案 0 :(得分:0)

你试过这个吗?

Projections.projectionList().add(Projections.count("username");