Escolar Documentos
Profissional Documentos
Cultura Documentos
com
tech facts at your fingertips
CONTENTS INCLUDE:
n
Getting Started With JPA
int id;
nothing more than a regular Java class with metadata to String name;
describe how its state maps to the database tables. Metadata @Column(name="PHONE_NUM")
may be in the form of annotations on the entity class itself, or it String phoneNumber;
may be an accompanying XML file, but we are using annotations @OneToOne
Address address;
since they are easier to specify and understand.
@OneToMany(mappedBy="owner")
List<Pet> pets;
...
Hot When used together, XML mappings can over- }
Tip ride the values specified in annotations
In a bidirectional relationship pair, such as the @OneToMany
relationship in Owner to Pet and the @ManyToOne relationship
Every entity class should have an @Entity marker and an back from Pet to Owner, only one foreign key is required in one
identifier field, indicated by @Id, that is mapped to the primary of the tables to manage both sides of the relationship. As a
key column in the database. When a field contains simple
general rule, the side that does not have the foreign key in it
data and maps to a regular column in the database we call it a
specifies a mappedBy attribute in the relationship annotation and
basic mapping, thus an identifier field is a special kind of basic
specifies the field in the related entity that maps the foreign key.
mapping. When an entity has a field that references one or more
→
other entities, that field maps to a foreign key column, and is
Getting Started with JPA
basic mapping field with @Column you can define the particular n Bonus content online
column that maps the state in that field. Likewise @JoinColumn n New issue every 1-2 weeks
@Basic @Enumerated @ManyToOne @Temporal The basic purpose of an entity manager is to perform create/
@Embedded @Lob @OneToMany @Transient read/update/delete (CRUD) operations on entities. Listing 5
@EmbeddedId @ManyToMany @OneToOne shows methods that perform these operations.
Listing 5 – Invoking the entity manager
Annotations used to override the names of the tables or
public Pet createPet(int idNum, String name, PetType
columns in the database are:
type) {
@AttributeOverride(s) @PrimaryKeyJoinColumn(s) Pet pet = new Pet(idNum, name, type);
@AssociationOverride(s) @SecondaryTable(s) em.persist(pet);
@Column @SequenceGenerator return pet;
@DiscriminatorColumn @Table }
@JoinColumn(s) @TableGenerator public Pet findPet(int id) {
@JoinTable return em.find(Pet.class, id);
}
Other annotations used to indicate the type of the class or public Pet changeName(int id, String newName) {
other aspects of the model are: Pet pet = this.findPet(id);
pet.setName(newName);
@Entity @IdClass @MappedSuperclass return pet;
@Embeddable @Inheritance @OrderBy }
@GeneratedValue @DiscriminatorValue @Version public void deletePet(int id) {
@Id @MapKey Pet pet = this.findPet(id);
em.remove(pet);
}
Obtaining an Entity Manager Note that finding the pet is the first step to being able to
perform update and delete operations on it. Also, an update
The EntityManager class is the main API in JPA. It is used does not even involve invoking the entity manager, but requires
to create new entities, manufacture queries to return sets reading the pet, loading it into the entity manager and then
of existing entities, merge in the state of remotely modified modifying it. The modification will be reflected in the database
entities, delete entities from the database, and more. when the transaction is committed.
There are, generally speaking, two main kinds of entity
managers:
The merge() method can also be used to create
container-managed The managed entity managers may only be obtained Hot entities, but is most useful for merging in entity
within a container that supports the JPA Service Tip
Provider Interface (SPI). changes made on the client side.
non-managed Non-managed entity managers may be obtained
in any environment where a JPA provider is on the
classpath. Listing 3 shows an example of obtaining
a non-managed entity manager by first obtaining Transactions
an EntityManagerFactory instance from the
Persistence root class.
Since we just mentioned transactions, but didn’t explain them,
Listing 3 – Obtaining a non-managed entity manager now would be a good time to state that JPA supports two
different kinds of transactions.
import javax.persistence.*;
... JTA container transactions Used when running in container mode
EntityManagerFactory emf = Persistence resource local transactions Typically used when running in non-container
.createEntityManagerFactory("PetShop"); mode.
EntityManager em = emf.createEntityManager();
... JTA transactions are started and committed using the usual
em.close(); container techniques, either calling the UserTransaction API
or making use of container-managed transaction demarcation
In Listing 4 we see how a standard host container can provide a
in EJB or Spring. For example, if the methods in Listing 5 were
simpler way to obtain an entity manager. The only catch is that
in a session bean that had a Required transaction attribute
this is only supported within standard Java EE components (or
containers that are compliant to the JPA container contract), so setting then a transaction would be started at the beginning and
committed at the end of each client method invocation.
this example uses a stateless session bean.
When using local transactions the transaction must be
Listing 4 – Injecting a managed entity manager
demarcated manually by invoking on the EntityTransaction
@Stateless
instance accessed from the entity manager. Each of the three
public class MyBean implements MyInterface {
@PersistenceContext(unitName="PetShop")
methods in Listing 5 that caused the database to change would
EntityManager em; need to have begin and commit calls, as shown in Listing 6 for
... the persist method. Methods that only read from the database
} do not need to occur within a transaction.
void flush(); Cause all changes to be written out to the The last identifier is prefixed with a colon (:) character to indicate
database
that it is a named parameter that must be bound at runtime
void setFlushMode( Set the flushing mode for query execution before the query can be executed. Listing 9 shows a method
FlushModeType flushMode);
that executes the query by first instantiating a Query object
FlushModeType getFlushMode(); Get the flushing mode for query execution
using the createNamedQuery() factory method, then binding
void lock( Lock an object to obtain greater isolation
O
bject entity, consistency guarantees
the pname named parameter to the name that was passed
LockModeType lockMode); into the method, and finally executing the query by invoking
void refresh(Object entity); Update the in-memory entity with the state getResultList().
from the database
Listing 9 – Executing a named query
void clear(); Make all managed entities become
unmanaged public List findAllPetsByName(String petName) {
boolean contains( Determine if an entity is managed Query q = em.createNamedQuery("Pet.findByName");
Object entity); q.setParameter("pname", petName);
Query createQuery( Create a dynamic query from JP QL return q.getResultList();
String JP QLString); }
Query createNamedQuery( Create a named query
String name);
Named queries are not only more efficient than
Query createNativeQuery( Create a query from SQL Hot dynamic queries but are also safer since they
String sqlString);
Tip
Query createNativeQuery( Create a query from SQL that returns a given will often get pre-compiled by the persistence
String sqlString,
Class entityClass);
entity type implementation at deployment time
Query createNativeQuery( Create a query from SQL that uses a given
S
tring sqlString, defined mapping The entire Query API is shown in Table 2.
String resultSetMapping);
Table 1. EntityManager method summary Query setHint( Set an implementation-specific query hint
String hintName,
Object value);
Object value);
Query setParameter( Bind an instance of java.util.Date to a
Dynamic queries are objects that are created from an entity S
tring name, named parameter
manager, and then executed. The query criteria are specified Date value,
TemporalType temporalType);
at creation time as a Java Persistence Query Language (JP
QL) string. Before executing the query a number of possible Table 2. Query method summary
The Java Persistence Query Language is SQL-like, but operates conditional_exp {[NOT] conditional} | {conditional_exp {AND | OR}
over the entities and their mapped persistent attributes instead conditional_exp}
of the SQL schema. Many of the SQL functions and even conditional comparison | between_exp | like_exp | in_exp | compare_
null_exp | compare_empty_exp | compare_member_exp |
reserved words are supported in JP QL. exists_exp
There are three basic types of JP QL statements, of which the comparison compare_string | compare_boolean | compare_enum |
compare_datetime | compare_entity | compare_arithmetic
first is monstrously the most popular and useful: selects, bulk
compare_string string_exp {= | > | >= | < | <= | <>} {string_exp | all_any_
updates and bulk deletes. subquery}
1. s
elect_clause from_clause [where_clause] [groupby_clause] compare_boolean boolean_exp {= | <>} {boolean_exp | all_any_subquery}
[having_clause] [orderby_clause] compare_enum enum_exp {= | <>} {enum_exp | all_any_subquery}
2. update_clause [where_clause]
compare_datetime datetime_exp {= | > | >= | < | <= | <>} {datetime_exp |
3. delete_clause [where_clause] all_any_subquery}
Bulk deletes are useful for doing test clean-up compare_arithmetic arithmetic_exp {= | > | >= | < | <= | <>} {arithmetic_exp |
Hot and clearing all of the data from the entity tables
all_any_subquery}
Tip all_any_subquery {ALL | ANY | SOME} ( subquery )
without having to revert to SQL.
between_exp arithmetic_exp [NOT] BETWEEN arithmetic_exp AND
arithmetic_exp
A simplified table of most of the supported syntax is in
like_exp string_exp [NOT] LIKE pattern_value [ESCAPE escape_char]
Table 4. For complete and precise grammar, consult the JPA
in_exp state_field_exp [NOT] IN ( {literal | input_param} {,{literal |
specification at http://jcp.org/aboutJava/communityprocess/ input_param}}* )
final/jsr220/index.html. The primitive terms are shown in Table 3. compare_null_exp {single_rel_exp | input_param} IS [NOT] NULL
entityName Name of an entity (which is defaulted to the name of the compare_member_exp entity_exp [NOT] MEMBER [OF] multi_rel_exp
entity class)
exists_exp [NOT] EXISTS ( subquery )
variable Identifier variable following Java identifier rules
state_field_exp Term that resolves to an entity field containing simple arithmetic_exp arithmetic | ( subquery )
state (e.g. if Pet is represented by variable p, then p.name
or p.owner.phoneNumber) string_exp string | ( subquery )
single_rel_exp Term that resolves to an entity field containing an one-to- entity_exp variable | input_param | single_rel_exp
one or many-to-one relationship (e.g. if Pet is represented
by variable p, then p.owner or p.owner.address) enum_exp enum | ( subquery )
multi_rel_exp Term that resolves to an entity field containing a one- datetime_ exp datetime | ( subquery )
to-many or many-to-many relationship (e.g. if Owner is
represented by variable o, then o.pets) boolean_exp boolean | ( subquery )
rel_field Term composed of a variable and one of its relationship
fields, with no traversing of intermediate relationships arithmetic arithmetic_term | {arithmetic { * | / | + | - } arithmetic}
(e.g. if Pet is represented by variable p, then p.owner)
arithmetic_term state_field_exp | literal | input_param | aggregate_exp |
constructor_method Constructor for a non-entity class (i.e. the name of the numeric_function | ( arithmetic )
class)
string state_field_exp | literal | input_param | aggregate_exp |
input_param Variable that represents an input parameter and must be string_function
bound before the query can be executed
literal A value of a particular type such as a string or integer (e.g. enum state_field_exp | literal | input_param
‘Iggy Pop’, or 42)
datetime state_field_exp | input_param | aggregate_exp | datetime_
pattern_value A valid SQL pattern string (e.g. “% Smith”) function
escape_char A character to be escaped boolean state_field_exp | literal | input_param
Configuration
persistence
*
Without counting the mappings from the entity to the database
tables, there is really only one unit of JPA configuration needed persistence-unit
to get your application up and running. It is based on the • name
• transaction type
notion of a persistence unit, and is configured in a file called
persistence.xml, which must always be placed in the META-
INF directory of your deployment unit. Each persistence unit is provider
a configuration closure over the settings necessary to run in the jta-data-source
relevant environment. The parent element in a persistence.xml
file is the persistence element and may contain one or more non-jta-data-source
Moving on Resources
As you may have noticed, using JPA is not that hard, and Resource Source
you win the big prizes of portability and compatibility going Glassfish Persistence Page https://glassfish.dev.java.net/javaee5/persistence/entity-
persistence-support.html
forward. Hopefully you are now feeling ready to cut your teeth
Oracle Technology Network http://www.oracle.com/technology/products/ias/toplink/
on a JPA application of your very own. The next step is to JPA resources jpa/index.html
download the open source JPA 1.0 Reference Implementation Eclipse JPA (part of Eclipse http://www.eclipse.org/eclipselink
(TopLink Essentials) and start it up. It is available at https:// Persistence Services Project)
glassfish.dev.java.net/downloads/persistence/JavaPersistence. Pro EJB 3: Java Persistence By Mike Keith and Merrick Schincariol
API Apress, 2006
html and is trivial to install and configure. Happy persisting! books.dzone.com/books/java-persistence
AB O U T T H E A U T H O R RECOMMENDED BOOK
DZone, Inc.
1251 NW Maynard
ISBN-13: 978-1-934238-24-0
Cary, NC 27513
ISBN-10: 1-934238-24-4
50795
888.678.0399
DZone communities deliver over 3.5 million pages per month to 919.678.0300
more than 1.5 million software developers, architects and designers.
Refcardz Feedback Welcome
DZone offers something for every developer, including news, refcardz@dzone.com
$7.95
tutorials, blogs, cheatsheets, feature articles, source code and more. Sponsorship Opportunities 9 781934 238240
“DZone is a developer’s dream,” says PC Magazine. sales@dzone.com
Copyright © 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, Version 1.0
photocopying, or otherwise, without prior written permission of the publisher. Reference: Pro EJB 3: Java Persistence API, Michael Keith and Merrick Schincariol, Apress, May 2006.