如何正确使用setProjection?

时间:2014-09-02 04:48:31

标签: hibernate

我想只检索UserAccount类中的某些列,所以我有以下代码:

UserAccount aUser = (UserAccount)currentSession().createCriteria(UserAccount.class)
                        /*  .setProjection(Projections.projectionList()
                                    .add(Projections.property("id"))
                                    .add(Projections.property("username"))
                                    .add(Projections.property("email"))
                                    .add(Projections.property("displayname"))) */
                            .add(Restrictions.eq("email", email))
                            .add(Restrictions.eq("password", password))
                            .add(Restrictions.eq("enabled", true))
                            .add(Restrictions.eq("role", Role.CUSTOMER))
                            .uniqueResult();
    System.out.println(aUser);
    return aUser;

我得到了null作为回报。但是如果我注释掉setProjections,我将获得具有所有属性的用户。在这种情况下,如何正确使用setProjection?

2 个答案:

答案 0 :(得分:0)

根据预测,我们应该使用结果转换器别名

UserAccount aUser = (UserAccount)currentSession()
    // FROM
    .createCriteria(UserAccount.class)
    // WHERE
    .add(Restrictions.eq("email", email))
    .add(Restrictions.eq("password", password))
    .add(Restrictions.eq("enabled", true))
    .add(Restrictions.eq("role", Role.CUSTOMER))
    // SELECT with alias
    .setProjection(Projections.projectionList()
       .add(Projections.property("id"),"id")             // alias is a must for
       .add(Projections.property("username"),"username") // result transformer
       .add(Projections.property("email"),"email")
       .add(Projections.property("displayname"),"displayname")
    )
    // here we go - this will convert projection into entity
    .setResultTransformer(Transformers.aliasToBean(UserAccount.class))
    .uniqueResult();

检查:

答案 1 :(得分:0)

它返回一个Object数组,因此代码应为:

Object[] rows = (Object[]) session
        .createCriteria(UserAccount.class)
        .setProjection(
                Projections.projectionList()
                        .add(Projections.property("id"))
                        .add(Projections.property("username"))
                        .add(Projections.property("email"))
                        .add(Projections.property("displayname")))
        .add(Restrictions.eq("email", email))
        .add(Restrictions.eq("password", password))
        .add(Restrictions.eq("enabled", true))
        .add(Restrictions.eq("role", Role.CUSTOMER))
        .uniqueResult();