从SQL视图转换Hibernate结果

时间:2014-10-12 12:20:15

标签: java hibernate hql hibernate-native-query

我创建了一个SQL视图,其中包含User的所有属性和一个"is_granted",它是布尔值,使用自定义pl / sql函数计算。在我的应用程序中,我需要创建本机SQL查询并将值映射到DTO对象。问题是,在转换期间抛出异常并且查询失败。

考虑以下模型:

@Entity
@Table("quasar_user")
public class User{

    private long id;
    private String firstname;
    private String lastname;
    private User changedBy;
    // a lot of others properties ...
}


public class UserDto{
    private User user;
    private boolean granted;

    // getters setters
}

查询 - 将属性映射到DTO

@SuppressWarnings("unchecked")
public List<UserDto> getGrantedUsers(final long userId){

    final String sql = 
            "SELECT u.* as user, u.is_granted as granted " + 
            "FROM user_view u " +
            "WHERE u.id= :userId ";

    return sessionFactory.getCurrentSession().createSQLQuery(sql)
        .addEntity("user", User.class)
        .addScalar("granted", StandardBasicTypes.BOOLEAN)
        .setLong("userId", userId)
        .setResultTransformer(Transformers.aliasToBean(UserDto.class))
        .list();

}

有人知道,问题出在哪里?转型有问题吗?

堆栈跟踪

CustomMappingExceptionResolver:doResolveException(line 37) - java.lang.NullPointerException
at org.hibernate.loader.DefaultEntityAliases.intern(DefaultEntityAliases.java:193)
at org.hibernate.loader.DefaultEntityAliases.getSuffixedPropertyAliases(DefaultEntityAliases.java:151)
at org.hibernate.loader.DefaultEntityAliases.determinePropertyAliases(DefaultEntityAliases.java:93)
at org.hibernate.loader.DefaultEntityAliases.<init>(DefaultEntityAliases.java:65)
at org.hibernate.loader.ColumnEntityAliases.<init>(ColumnEntityAliases.java:43)
at org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.generateCustomReturns(SQLQueryReturnProcessor.java:198)
at org.hibernate.loader.custom.sql.SQLCustomQuery.<init>(SQLCustomQuery.java:152)
at org.hibernate.engine.query.spi.NativeSQLQueryPlan.<init>(NativeSQLQueryPlan.java:67)
at org.hibernate.engine.query.spi.QueryPlanCache.getNativeSQLQueryPlan(QueryPlanCache.java:197)
at org.hibernate.internal.AbstractSessionImpl.getNativeSQLQueryPlan(AbstractSessionImpl.java:226)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:232)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:157)
at cz.nlfnorm.quasar.dao.impl.UseDaoImpl.getGrantedUsers(UseDaoImpl.java:234)

1 个答案:

答案 0 :(得分:2)

我的SQL查询错误。纠正后:

final String sql = 
        "SELECT {u.*}, u.is_granted as granted " + 
        "FROM user_view u " +
        "WHERE u.id= :userId ";

有关详细信息,请参阅: Table 16.1. Alias injection names