Professional Documents
Culture Documents
Rc022 JPA Online
Rc022 JPA Online
com
#22
Mapping an Object
Transactions
Querying
@Entity
@Table(name="PET_INFO")
public class Pet {
@Id
@Column(name="ID")
int licenseNumber;
String name;
PetType type;
@ManyToOne
@JoinColumn(name="OWNER_ID")
Owner owner;
...
}
The Java Persistence API (JPA) is the Java standard for mapping
Java objects to a relational database. Even though proprietary
mapping products like Hibernate and TopLink still exist, they
are now focused on providing their functionality through
the JPA API, allowing all applications to be portable across
JPA implementations. This refcard will give users enough
to understand the basics of JPA and get started writing JPA
applications. It covers entities, identifiers, O-R mappings,
using an entity manager, creating and executing queries, and
configuration of the persistence.xml file.
www.dzone.com
MAPPING AN OBJECT
The basic unit of persistence in JPA is the entity, which is
nothing more than a regular Java class with metadata to
describe how its state maps to the database tables. Metadata
may be in the form of annotations on the entity class itself, or it
may be an accompanying XML file, but we are using annotations
since they are easier to specify and understand.
Hot
Tip
When used together, XML mappings can override the values specified in annotations
Defaulting rules in JPA mean that you are not required to specify
table names and column names that an entity is mapped to. If
you are not happy with the JPA-assigned defaults then you can
always override them through the use of additional mapping
metadata. For example, by putting @Table on the entity class
you can make the table name explicit, and by annotating a
basic mapping field with @Column you can define the particular
column that maps the state in that field. Likewise @JoinColumn
is used to override the name of the foreign key column for
relationship references.
Authoritative content
Designed for developers
n Written by top experts
n Latest tools & technologies
n Hot tips & examples
n Bonus content online
n New issue every 1-2 weeks
n
n
www.dzone.com
@Enumerated
@Lob
@ManyToMany
@ManyToOne
@OneToMany
@OneToOne
@Temporal
@Transient
@PrimaryKeyJoinColumn(s)
@SecondaryTable(s)
@SequenceGenerator
@Table
@TableGenerator
@IdClass
@MappedSuperclass
@Embeddable
@Inheritance
@OrderBy
@GeneratedValue
@DiscriminatorValue
@Version
@Id
@MapKey
Note that finding the pet is the first step to being able to
perform update and delete operations on it. Also, an update
does not even involve invoking the entity manager, but requires
reading the pet, loading it into the entity manager and then
modifying it. The modification will be reflected in the database
when the transaction is committed.
non-managed
Hot
Tip
TRANSACTIONS
Since we just mentioned transactions, but didnt explain them,
now would be a good time to state that JPA supports two
different kinds of transactions.
www.dzone.com
Querying, continued
Transactions, continued
Listing 6 Using EntityTransaction
Description
Persist an entity
<T> T find(
Class<T> entityClass,
Object primaryKey);
<T> T getReference(
Class<T> entityClass,
Object primaryKey);
void flush();
void setFlushMode(
FlushModeType flushMode);
FlushModeType getFlushMode();
void lock(
Object entity,
LockModeType lockMode);
void clear();
boolean contains(
Object entity);
Query createQuery(
String JP QLString);
Query createNamedQuery(
String name);
Query createNativeQuery(
String sqlString);
Query createNativeQuery(
String sqlString,
Class entityClass);
Query createNativeQuery(
String sqlString,
String resultSetMapping);
void joinTransaction();
Object getDelegate();
void close();
boolean isOpen();
EntityTransaction
getTransaction();
Hot
Tip
QUERYING
Dynamic queries are objects that are created from an entity
manager, and then executed. The query criteria are specified
at creation time as a Java Persistence Query Language (JP
QL) string. Before executing the query a number of possible
DZone, Inc.
Query Method
Description
List getResultList();
Object getSingleResult();
int executeUpdate();
Query setMaxResults(
int maxResult);
Query setFirstResult(
int startPosition);
Query setHint(
String hintName,
Object value);
Query setParameter(
String name,
Object value);
Query setParameter(
S
tring name,
Date value,
TemporalType temporalType);
www.dzone.com
Querying, continued
Query Method
Description
Clause/Term
Syntax
Query setParameter(
String name,
Calendar value,
TemporalType temporalType);
select_clause
select_exp
Query setParameter(
int position,
Object value);
aggregate_exp
Query setParameter(
int position,
Date value, TemporalType
temporalType);
constructor_exp
Query setParameter(
int position,
Calendar value, TemporalType
temporalType);
constructor_item
single_rel_exp | aggregate_exp
from_clause
Query setFlushMode(
FlushModeType flushMode);
variable_decl
join_exp
fetch_join_exp
in_decl
where_clause
WHERE conditional_exp
conditional_exp
conditional
comparison
compare_string
1. s
elect_clause from_clause [where_clause] [groupby_clause]
[having_clause] [orderby_clause]
2. update_clause [where_clause]
3. delete_clause [where_clause]
compare_boolean
compare_enum
compare_datetime
compare_entity
compare_arithmetic
all_any_subquery
between_exp
like_exp
in_exp
compare_null_exp
Hot
Tip
Description
compare_empty_exp
entityName
compare_member_exp
exists_exp
variable
state_field_exp
arithmetic_exp
arithmetic | ( subquery )
string_exp
string | ( subquery )
Term that resolves to an entity field containing an one-toone or many-to-one relationship (e.g. if Pet is represented
by variable p, then p.owner or p.owner.address)
entity_exp
enum_exp
enum | ( subquery )
multi_rel_exp
Term that resolves to an entity field containing a oneto-many or many-to-many relationship (e.g. if Owner is
represented by variable o, then o.pets)
datetime_ exp
datetime | ( subquery )
boolean_exp
boolean | ( subquery )
rel_field
arithmetic
arithmetic_term
string
enum
datetime
boolean
single_rel_exp
constructor_method
input_param
literal
pattern_value
escape_char
A character to be escaped
DZone, Inc.
www.dzone.com
Configuration, continued
Clause/Term
Syntax
string_function
datetime_function
numeric_function
LENGTH ( string ) |
LOCATE ( string , string [ , arithmetic] ) |
ABS ( arithmetic ) |
SQRT ( arithmetic ) |
MOD ( arithmetic , arithmetic ) |
SIZE ( multi_rel_ exp )
subquery
subquery_decl
update_clause
update_item
new_value
delete_clause
groupby_clause
groupby_item
single_rel_exp | variable
having_clause
HAVING conditional_exp
orderby_clause
orderby_item
Hot
Tip
Hot
Tip
CONFIGURATION
persistence
*
persistence-unit
name
transaction type
provider
jta-data-source
non-jta-data-source
mapping-file
jar-file
class
exclude-unlisted-classes
properties
www.dzone.com
property
name
value
MOVING ON
RESOURCES
As you may have noticed, using JPA is not that hard, and
you win the big prizes of portability and compatibility going
forward. Hopefully you are now feeling ready to cut your teeth
on a JPA application of your very own. The next step is to
download the open source JPA 1.0 Reference Implementation
(TopLink Essentials) and start it up. It is available at https://
glassfish.dev.java.net/downloads/persistence/JavaPersistence.
html and is trivial to install and configure. Happy persisting!
Resource
Source
https://glassfish.dev.java.net/javaee5/persistence/entitypersistence-support.html
http://www.oracle.com/technology/products/ias/toplink/
jpa/index.html
http://www.eclipse.org/eclipselink
RECOMMENDED BOOK
Mike Keith
Mike Keith was a co-lead of the EJB 3.0 and JPA 1.0 specifications and coauthored the premier JPA reference book called Pro EJB 3: Java Persistence
API. He has 18 years of teaching, research and development experience in
object-oriented and distributed systems, specializing in object persistence. He
currently works as an architect for Java and persistence strategies at Oracle
and represents Oracle on the JPA 2.0 and Java EE 6 expert groups. He has
authored a host of articles and papers and is a popular speaker at numerous conferences and
events around the world.
Publications
n
n
n
n
Current projects:
n
n
n
n
n
BUY NOW
books.dzone.com/books/java-persistence
Available:
Core Seam
Essential Ruby
Essential MySQL
Core .NET
Equinox
Spring Annotations
C#
EMF
Core Java
Groovy
PHP
JavaServer Faces
Silverlight 2
Hibernate Search
XML
Struts2
FREE
Design Patterns
Published June 2008
DZone, Inc.
1251 NW Maynard
Cary, NC 27513
ISBN-13: 978-1-934238-24-0
ISBN-10: 1-934238-24-4
50795
888.678.0399
919.678.0300
Refcardz Feedback Welcome
refcardz@dzone.com
Sponsorship Opportunities
sales@dzone.com
$7.95
9 781934 238240
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,
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.
Version 1.0