Java EE 8 By Example
  • Introduction
  • Overview
    • Example Codes
  • JSF 2.3
    • Activating CDI in JSF 2.3
    • Run applications in JSF 2.2 compatible mode
    • CDI alignment
    • CDI compatible @ManagedProperty
    • Inject support in Converter, Validator and Behavor
    • Websocket support
    • UIData improvements
    • Class level bean validation with f:valdiateWholeBean
    • Java 8 DateTime support
    • PostRenderViewEvent: publising events after view is rendered
    • Search expression framework
  • CDI 2.0
    • Java SE support
    • Event Priority
    • Async Events
    • Register Beans dynamicially
    • Configurators and Intercept Producers
  • JPA 2.2
    • Java 8 Datetime support
    • Return Stream based result from Query
    • More CDI Alignments
  • JSON-B 1.0
  • JSON-P 1.1
  • Bean Validation 2.0
  • JAXRS 2.1
    • Async improvements
    • Server Sent Event
    • Reactive Client
  • Java EE Security API 1.0
    • HttpAuthenticationMechanism
    • IdentityStore
    • SecurityContext
  • Servlet 4.0
    • Server Push
    • Runtime Discovery of Servlet Mappings
    • Http Trailer
  • MVC 1.0
    • Getting started with MVC
    • Handling form submission
    • Exception handling and form validation
    • Processing PUT and DELETE methods
    • Page navigation
    • MVC and CDI
    • Security
    • Bean parameter conversion
    • View engine
Powered by GitBook
On this page

Was this helpful?

  1. JPA 2.2

Return Stream based result from Query

PreviousJava 8 Datetime supportNextMore CDI Alignments

Last updated 4 years ago

Was this helpful?

Hibernate has already added a lot of , 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.

@Stateless
public class PostRepository extends AbstractRepository<Post, Long> {

    @PersistenceContext
    private EntityManager entityManager;

    public List<Post> findByKeyword(String keyword) {
        return stream().filter(p -> p.getTitle().contains(keyword) || p.getContent().contains(keyword))
                .collect(toList());
    }

    public long countByKeyword(String keyword) {
        return stream().filter(p -> p.getTitle().contains(keyword) || p.getContent().contains(keyword))
                .count();
    }

    @Override
    protected EntityManager entityManager() {
        return this.entityManager;
    }

}

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

public abstract class AbstractRepository<T extends AbstractEntity, ID> {

    protected abstract EntityManager entityManager();

    private Class<T> entityClass() {
        ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();
        return (Class<T>) parameterizedType.getActualTypeArguments()[0];
    }

    public List<T> findAll() {

        CriteriaBuilder cb = this.entityManager().getCriteriaBuilder();

        CriteriaQuery<T> q = cb.createQuery(entityClass());
        Root<T> c = q.from(entityClass());

        return entityManager().createQuery(q).getResultList();
    }

    public T save(T entity) {
        if (entity.getId() == null) {
            entityManager().persist(entity);

            return entity;
        } else {
            return entityManager().merge(entity);
        }
    }

    public T findById(Long id) {
        return entityManager().find(entityClass(), id);
    }

    public void delete(T entity) {
        T _entity = entityManager().merge(entity);
        entityManager().remove(_entity);
    }

    public Stream<T> stream() {
        CriteriaBuilder cb = this.entityManager().getCriteriaBuilder();
        CriteriaQuery<T> q = cb.createQuery(entityClass());
        Root<T> c = q.from(entityClass());

        return entityManager().createQuery(q).getResultStream();
    }

    public Optional<T> findOptionalById(Long id) {
       return Optional.ofNullable(findById(id));
    }

}

Grab the from my GitHub account, and have a try.

alignments with Java 8
source codes