Hibernate: Criteria & createSQLQuery: how to get proper JSON?
Mr P. The question was asked: Apr 15, 2020. 04:56
1 answer
When I try this I get the proper JSON as a result, but it takes a lot of time:
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;
and the JSON is like:
[{"id":111,"name":"Name111"},{"id":222,"name":"Name222"}]
In attempt to improve performance I tried code below. In SQL app the results are OK, a few records of users:
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;
Now the 'JSON' however looks like this:
[[111,"Name111"],[222,"Name222"]]
I tried several things, like select *
, criteria.add(Restrictions...)
but to no effect. What I noticed is that in the first case specialUsers.toString
returns proper data, in the second case it returns meaningless Strings like Ljava.lang.Object;@23e1469f
.
Any hints how to solve this?