java - Hibernate: Criteria & createSQLQuery: 如何得到正确的 JSON?
问题描述
当我尝试这个时,我得到了正确的 JSON,但这需要很多时间:
Criteria c = sessionFactory.getCurrentSession().createCriteria(User.class);
List<User> users = c.list();
List<User> specialUsers = new ArrayList<>();
for (User user : users) {
List<Perm> userPerms = user.getProfile().getPerms();
for (Perm perm : userPerms) {
if (perm.getId().equals(SPECIAL_ID)) {
specialUsers.add(user);
}
}
}
return specialUsers;
JSON就像:
[{"id":111,"name":"Name111"},{"id":222,"name":"Name222"}]
为了提高性能,我尝试了下面的代码。在 SQL 应用程序中,结果是好的,一些用户记录:
String sql = "SELECT u.id, u.name FROM app.user u inner join app.perms p where u.profile = p.profile AND p.right= :rightId";
List<User> specialUsers= (List<User>)sessionFactory.getCurrentSession()
.createSQLQuery(sql)
.setParameter("rightId", SPECIAL_ID)
.list();
return specialUsers;
然而,现在“JSON”看起来像这样:
[[111,"Name111"],[222,"Name222"]]
我尝试了几件事,例如select *
,criteria.add(Restrictions...)
但没有效果。我注意到的是,在第一种情况下specialUsers.toString
返回正确的数据,在第二种情况下,它返回无意义的字符串,如Ljava.lang.Object;@23e1469f
.
任何提示如何解决这个问题?
解决方案
我设法以这种方式解决了这个问题,可能并不完美:
// get ids of all special users
String sql = "SELECT u.id FROM app.user u inner join app.perms p where u.profile = p.profile AND p.right= :rightId";
List<Integer> intIds = sessionFactory.getCurrentSession()
.createSQLQuery(sql)
.setParameter("rightId", SPECIAL_ID)
.list();
// convert to long values
List<Long> longIds = intIds.stream()
.mapToLong(Integer::longValue)
.boxed().collect(Collectors.toList());
// get all special users
Criteria c = sessionFactory
.getCurrentSession()
.createCriteria(User.class)
.add(Restrictions.in("id", longIds));
List<User> specialUsers = c.list();
return specialUsers;
}
推荐阅读
- javascript - 单击项目或失去焦点时关闭 javascript 菜单
- reactjs - 即使获取成功,方法返回未定义?
- android - 在我的 viewModel 中测试函数的最佳方法是什么?
- javascript - 有没有办法添加自定义 SVG 路径以充当网页中的光标?
- ruby - LRTHWx46,“mkdir bin data doc ext lib tests lib/NAME”有什么作用?如果我不知道预期的结果,我无法推理我的解决方案
- ios - 尝试设置非属性列表对象的用户默认错误
- python - 在 python 中创建一个食物板
- python - Python replace function, Can it be done more beautiful?
- python - 日期时间列在 mm/dd/yyyy 中,需要 dd/mm/yyyy
- angularjs - 使用AngularJS单击按钮时如何清除输入字段?