Java Reference
In-Depth Information
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 previous 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 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.
Entity Relationships
There are several annotations we can use in JPA entities to define relationships
between them. In our Customer entity shown above, we can see that the wizard
detected several one-to-many relationships in the CUSTOMER table, and automatically
added the @OneToMany annotation to define these relationships in our entity. Notice
that each field annotated with the @OneToMany annotation is of type java.util.
Collection . The Customer is the "one" side of the relationship, since a customer can
have many orders, many addresses (street, mail), or many telephone numbers (home,
work, cell). Notice that the wizard uses generics to specify the type of objects we can
add to each collection. Objects in these collections are the JPA entities mapping to the
corresponding tables in our database schema.
Notice that @OneToMany annotation has a mappedBy attribute. This attribute is
necessary since each of these relationships is bi-directional (we can access all
addresses for a customer, and for a given address, we can obtain what customer it
belongs to). The value of this attribute must match the name of the field on the other
side of the relationship. Let's take a look at the Address entity to illustrate the other
side of the customer-address relationship.
 
Search WWH ::




Custom Search