2

我创建了一个 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)
4

1 回答 1

2

My SQL query was wrong. After correction is:

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

For more details see: Table 16.1. Alias injection names

于 2014-10-12T18:22:05.357 回答