Java Reference
In-Depth Information
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;
}
}
Here we see a DAO object containing a method that will return a list of Customer
entities for customers whose last name equals 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 above code snippet, this can
be accomplished by invoking the createNamedQuery() method in EntityManager ,
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 , named parameters are
"placeholders" we can use to substitute for appropriate values.
In our example, we set the lastName named parameter in JPQL query with the
someLastName argument passed to our method.
Once we have populated all 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, notice 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. In addition to
allowing us to specify what column each field maps to, the @Column annotation has
a nullable attribute that allows us to specify if the column accepts null values or
not. As we can see, the wizard automatically sets nullable to false for the entity's
primary key field.
 
Search WWH ::




Custom Search