Java Reference
In-Depth Information
JPQL is a JPA-specific query language; its syntax is similar to SQL. The New Entity
Classes from Database wizard generates a JPQL query for each field in our entity.
When the query is executed, a list containing all instances of our entity that match
the criteria in the query will be returned. The following code snippet illustrates
this process:
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class CustomerDAO {
public List findCustomerByLastName(String someLastName)
//code to lookup EntityManager omitted for brevity
Query query =
query.setParameter("lastName", someLastName);
List resultList = query.getResultList();
return resultList;
Here, we see a DAO object that contains a method that will return a list of Customer
entities for customers whose last name is same as the one provided in the method's
parameter. In order to implement this, we need to obtain an instance of an object of
type javax.pesistence.Query . As we can see in the preceding code snippet, this can
be accomplished by invoking the createNamedQuery() method in EntityManager
and passing the query name (as defined in the @NamedQuery annotation) as a
parameter. Notice that the named queries generated by the NetBeans wizard contain
strings preceded by a colon ( : ). These strings are named parameters , which act like
placeholders that we can use to substitute for appropriate values.
In our example, we set the lastName named parameter in the JPQL query with the
someLastName argument passed to our method.
Once we have populated all the parameters in our query, we can obtain a list of all
matching entities by invoking the getResultList() method in our Query object.
Going back to our generated JPA entity, we can see that the wizard automatically
placed the @Id annotation in the field mapping to the table's primary key.
Additionally, each field is decorated with the @Column annotation, which allows
us to follow standard naming conventions in both the relational database and
Java worlds.
Search WWH ::

Custom Search