- Selecting Instances from a Single Entity
- Binding Parameters to a JPQL Query
- Integrating JPQL into Your Application
- Summary
Integrating JPQL into Your Application
To perform dynamic queries in your managed beans or domain model classes that are entities, you can use Entity Manager's create method:
Query query = em.createQuery("SELECT u FROM User u"); List<User> users = query.getResultList();
One of the nice things about using JPA is you don't have use JNDI (Java Naming and Directory Service) to create an instance for your entity. With JPA, a simple annotation does this, something referred to as dependency injection. Before, with older EJB frameworks, you had to use callback interfaces and bind the data-source to the bean using the bean's descriptor. JPA eliminates all this. If you're using parameters, the Query object has the setParameter method for assigning parameter values.
You can also do named queries with Entity Manager. These are static queries used in your code that you can refer to with a more descriptive name. You define these queries at the top of your entity classes:
@Entity @Name dQuery(name = "findAll", query="select u from User u") public class User { ... }
Now when we want to return all users from some method in the User class, all we have to do is using the following syntax:
Query query = em.createQuery("findAll");