首页 > 解决方案 > 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.

任何提示如何解决这个问题?

标签: javasqljsonspringhibernate

解决方案


我设法以这种方式解决了这个问题,可能并不完美:

        // 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;
    }






推荐阅读