Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Criteria queries in EJB 3

Can I use Criteria queries with EJB3 entities? If so, how can I combine them with EntityManager?

like image 290
user132371 Avatar asked Oct 16 '09 13:10

user132371


People also ask

Why Criteria API is deprecated?

The Criteria API allows us to build up a criteria query object programmatically, where we can apply different kinds of filtration rules and logical conditions. Since Hibernate 5.2, the Hibernate Criteria API is deprecated, and new development is focused on the JPA Criteria API.

What is Criteria query in JPA?

The Criteria API is a predefined API used to define queries for entities. It is the alternative way of defining a JPQL query. These queries are type-safe, and portable and easy to modify by changing the syntax. Similar to JPQL it follows abstract schema (easy to edit schema) and embedded objects.

What is Criteria query in Java?

The Criteria API is used to define queries for entities and their persistent state by creating query-defining objects. Criteria queries are written using Java programming language APIs, are typesafe, and are portable. Such queries work regardless of the underlying data store.

Why We Use Criteria query in Hibernate?

Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection() Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.


2 Answers

One of the new features introduced in the JPA 2.0 is the Criteria API. You need one of the JPA2 implementations:

  • Hibernate 3.5 now has JPA2 support
  • EclipseLink (reference JPA2 implementation)
  • Apache OpenJPA 2.0

Criteria queries are accessed through the EntityManager.getCriteriaBuilder(), and executed through the normal Query API.

EntityManager em = ...;
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> query = qb.createQuery(Employee.class);
Root<Employee> employee = query.from(Employee.class);
query.where(qb.equal(employee.get("firstName"), "Bob"));
List<Employee> result = em.createQuery(query).getResultList();
like image 187
Jacek S Avatar answered Sep 18 '22 15:09

Jacek S


JPA 2 (providing the criteria API) was defined in JSR 317 which can be regarded as successor to JSR 220 (the original EJB/JPA specification). Hence your comment "True. But that's not part of JPA 1.0/EJB 3.0 which is what the question was about." is irrelevant as you can use JPA 2 interchangeably on all common application servers (WebLogic, JBOSS, Glassfish, etc.) Green field projects will use JPA 2.0 or later. You will find many projects implemented using JPA 1 but most companies are in the process of replacing the JPA 1 framework.

like image 24
John Penner Avatar answered Sep 20 '22 15:09

John Penner