All posts tagged jpa

  • JPA Criteria and JPQL

    JPA2 introduced its “Criteria” queries, providing an API for typesafe query generation without the need to hardcode field names etc in queries; it built on the approach of Hibernate Criteria.
    In these examples we have two classes, Inventory and Product, where Inventory has a set of products.

    Select of persistable objects with simple filter

    JPQL single-string would be

    SELECT p FROM Product p WHERE p.name = 'MP3 Extra'

    JPA Criteria would be

    CriteriaQuery criteria = builder.createQuery(Product.class);
    Root productRoot = criteria.from(Product.class);
    criteria.select(productRoot);
    criteria.where(builder.equal(productRoot.get(Product_.name), "MP3 Extra"));
    List products = em.createQuery(criteria).getResultList();

    JPQL single-string would be

    SELECT p.value, p.manufacturer FROM Product p WHERE p.name = 'MP3 Extra'

    JPA Criteria would be

    CriteriaQuery criteria = builder.createQuery();
    Root productRoot = criteria.from(Product.class);
    criteria.multiselect(productRoot.get(Product_.value),
    productRoot.get(Product_.manufacturer);
    criteria.where(builder.equal(productRoot.get(Product_.name), "MP3 Extra"));
    List <Object[]> results = em.createQuery(criteria).getResultList();

    Select of aggregate of attribute of persistable objects

    JPQL single-string would be
    Read more