Java Reference
In-Depth Information
( CUSTOMERS ), but it makes sense to name our entities in singular ( Customer ).
Additionally, the standard naming convention for database tables containing more
than one word is to use underscores to separate words ( CUSTOMER_ORDER ) where
in Java the standard is to use camel case ( CustomerOrder ). The @Table annotation
allows us to follow established naming standards in both the relational database and
the Java worlds.
Named Queries and JPQL
Next, we see the @NamedQueries annotation (this annotation is only generated if we
click on the Generate Named Query Annotations for Persistent Fields checkbox
of the New Entity Classes from Database wizard). This query contains a value
attribute (the attribute name can be omitted from the code since it is the only
attribute in this annotation). The value of this attribute is an array of @NamedQuery
annotations. The @NamedQuery annotation has a name attribute, which is used to give
it a logical name (By convention, the JPA entity name is used as part of the query
name. As we can see in the generated code, the New Entity Classes from Database
wizard follows this convention), and a query attribute, which is used to define a Java
Persistence Query Language (JPQL) query to be executed by the named query.
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 =
em.createNamedQuery("Customer.findByLastName");
query.setParameter("lastName", someLastName);
List resultList = query.getResultList();
return resultList;
}
}
 
Search WWH ::




Custom Search