开发者

When selecting a subset of a table, hibernate does not auto cast it into the business domain object in a list

When i am selecting a full table

i.e. select * from product

, Hibernate returns me a list of Product objects. However, when i am selecting only a subset of it,

i.e. select name, price from product

, Hibernate returns me a list of objects which it is unable to cast it into a list of Product objects out of the box. Any attempts to cast it into a list of Product objects causes ClassCastException.

@SuppressWarnings("unchecked")
@Override
public List<UserRoleAndProgramCategory> get(int roleId, int programCategoryId) {
    String sHql;
    String[] key;
    Object[] value;

    key = new String[] { "roleId", "programCategoryId" };
    value = new Integer[] { roleId, programCategoryId };

    sHql = "select distinct l.userId, l.userName, l.fullName, l.roleId, l.roleName, l.roleCode, l.programCategoryId, l.programCategoryCode, l.pro开发者_JS百科gramCategoryDescription from "
            + UserRoleAndProgramCategory.class.getName()
            + " as l where roleName <> ' ' and roleCode not in ('CONTRACTOR', 'ADMIN') and programCategoryId = :programCategoryId and roleId = :roleId";

    return (List<UserRoleAndProgramCategory>) super.getQueryWithCache(sHql, key, value, false, false, false)
            .getQueryResult();
}

Thank you. Please let me know where i have went wrong.


Please read the docs.

In order to return a list of objects from a query that selects specific properties, you need to use an Alias To Bean transformer.

Example (for SQL queries, but HQL works the same)


sHql = "select distinct new UserRoleAndProgramCategory(l.userId, l.userName, l.fullName, l.roleId, l.roleName, l.roleCode, l.programCategoryId, l.programCategoryCode, l.programCategoryDescription) from "
            + UserRoleAndProgramCategory.class.getName()
            + " as l where roleName <> ' ' and roleCode not in ('CONTRACTOR', 'ADMIN') and programCategoryId = :programCategoryId and roleId = :roleId";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜