当我尝试这个时,我得到了正确的 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;
}
关于java - Hibernate:Criteria 和 createSQLQuery:如何获取正确的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61234328/