当选择表的子集时,hibernate 不会自动将其转换为列表中的业务域对象
当我选择整张桌子时
即从产品中选择*
,Hibernate 返回一个 Product 对象列表。然而,当我只选择其中的一个子集时,
即从产品中选择名称、价格
,Hibernate 返回一个对象列表,它无法将其转换为开箱即用的 Product 对象列表。任何将其转换为 Product 对象列表的尝试都会导致 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.programCategoryDescription 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();
}
谢谢。请让我知道我哪里出错了。
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.programCategoryDescription 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请阅读文档。
为了从选择特定属性的查询中返回对象列表,您需要使用 Alias To Bean 转换器。
示例(适用于 SQL 查询,但 HQL工作原理相同)
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)