Return Stream based result from Query

Hibernate has already added a lot of alignments with Java 8arrow-up-right, Stream and Optional are supported.

JPA 2.2 add official support for Stream result of query.

The following codes demonstrates query posts by keyword in JPA 2.1.

public List<Post> findByKeyword(String keyword) {
    CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();

    CriteriaQuery<Post> q = cb.createQuery(Post.class);
    Root<Post> c = q.from(Post.class);

    List<Predicate> predicates = new ArrayList<>();

    if (null != keyword && "".equals(keyword.trim())) {
        predicates.add(
                cb.or(
                        cb.like(c.get(Post_.title), '%' + keyword + '%'),
                        cb.like(c.get(Post_.content), '%' + keyword + '%')
                )
        );
    }

    q.where(predicates.toArray(new Predicate[predicates.size()]));

    TypedQuery query = this.entityManager.createQuery(q);

    return query.getResultList();
}

This can be simplified in JPA 2.2. The following is the complete codes of PostRepository.

And AbstractRepository is a generic Repository class can be reused for all entities.

Grab the source codesarrow-up-right from my GitHub account, and have a try.

Last updated