java hibernate标准投影rowCount只有1列



我有一个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=?)

这个方法比我的好吗?

有更好的吗?

我知道我正在检查属性不为空…

select count(name)

谢谢。

你试过吗?

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

最新更新