在休眠状态下具有列表的DTO

时间:2018-08-09 17:12:54

标签: java hibernate java-ee

我试图在包含集合的HQL中制作DTO构造器,但是我没有成功(首先,由于这个原因,您不能限制请求中的行数,其次,我的构造函数不接受该集合)< / p>

然后,我决定编写第二个标签请求,并将其附加到Post DTO:

@Override
    public List<SmallPostTransfer> findSmallPosts(int postStart, String search) {
        Query<SmallPostTransfer> query = session.createNamedQuery(PostsInfo.FIND_SMALL_POSTS, SmallPostTransfer.class)
                .setParameter("search", "%" + search.replace(" ", "%%") + "%")
                .setFirstResult(postStart)
                .setMaxResults(10);

        /*List of posts dto*/
        List<SmallPostTransfer> posts = query.getResultList();

        /*All id posts for tags*/
        StringBuilder numPosts = new StringBuilder();

        /*Map with all posts by them id*/
        Map<Long, SmallPostTransfer> postMap = new HashMap<>();
        posts.forEach( post -> {
            postMap.put(post.getId(), post);
            numPosts.append(post.getId()).append(",");
        });
        /*Delete the last comma*/
        numPosts.deleteCharAt(numPosts.length()-1);

        /*List of all tags for posts*/
        List<Object[]> tags =
                session.createNativeQuery("select pt.post_id, t.tag_id, t.name, t.description  from Tags t " +
                        " left join PostsTags pt on t.tag_id = pt.tag_id " +
                        " where pt.post_id in ("+numPosts+") ")
                        .getResultList();

        /*Attach tags to posts*/
        tags.forEach( tag -> {
            postMap.get(((BigInteger)tag[0]).longValue()).getTags()
                    .add(new TagTransfer(((BigInteger)tag[1]).longValue(), tag[2].toString(), tag[3].toString()));
        });

        return new ArrayList<>( postMap.values() );
    }

它有效,但是我想知道是否有办法更好,更有效地完成它,也许我对Hibernate不了解,我会很乐意提供帮助

0 个答案:

没有答案