Java Reference
In-Depth Information
//methods (equals,() hashCode() and toString() omitted for
brevity.
}
As we can see, NetBeans generates a class decorated with the @Entity annotation,
that marks the class as a JPA entity. Notice that NetBeans automatically decorated
one of the fields with the @Id annotation, based on the primary key constraint in
the table used to generate the JPA entity. Notice that no primary key generation
strategy is used, we either need to populate the primary key ourselves, or add the
@GeneratedValue annotation manually.
Notice the @Table annotation, this is an optional annotation that indicates what table
our JPA entity maps to. If the @Table annotation is not used, then our entity will map
to a table having the same name as the entity class (case insensitive). In our particular
example, the @Table annotation is redundant, but there are cases where it is useful.
For example, some database schemas have tables named in plural (i.e. 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 (i.e. CUSTOMER_ORDER ) where in Java the standard
is to use camel case (i.e. 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 {
 
Search WWH ::




Custom Search