Title: Java EE 5 BluePrints
1(No Transcript)
2Java EE 5 BluePrints
- Part 1 Java Persistence API
(Delete this element) Place your picture here
Brian Leonard Java Technology Evangelist Sun Mic
rosystems, Inc.
(Delete this element) If applicable, place your
company logo
3Overall Presentation Goal
Learn Best Practices for using the Java
Persistence API
4Speakers Qualifications
- Brian Leonard, a Senior Software Engineer at Sun
Microsystems, has been working with enterprise
Java since his days at NetDynamics before there
were any standards.
5Java EE 5 Goal
Make it easier to develop Java EE applications
Especially when first getting started with Java
EE
6JPA Programming Model
- Web-only Use
- Primary Keys
- Named Queries
- Model Facade
7JPA Programming Model
- Web-only Use
- Primary Keys
- Named Queries
- Model Facade
8A Web-Only App
- Doesn't have EJBs
- Runs in a Java EE 5 Container
- Servlet 2.5
9Entity Manager Decision
- Container Managed
- Application Managed
10Web-Only Use
- With either choice note
- Transactions must be managed by the developer
- Unlike with EJBs where they can be managed by the
container
- _at_Resource UserTransaction utx
- Begin(), Commit(), rollback()
- The entity manger must be used in a thread-safe
manner
11Container-Managed EM
- Usually obtained using JNDI
- _at_PersistenceContext annotation is also available
- However, annotations cannot be used inside of a
method.
- And creating an EM at the instance level is not
thread-safe
- Lifecyle managed by the container
- So slightly less code
12Container-Managed EM
_at_PersistenceContext(name"persistence/CatPc",
unitName"CatalogPu") public class CatalogFacade
implements ServletContextListener
_at_Resource UserTransaction utx pri
vate EntityManager getEntityManager()
EntityManager em null
try Context ctx new Initial
Context() em (EntityManager) ctx.lo
okup("javacomp/env/persistence/CatPc")
catch (NamingException ex)
throw new RuntimeException("Error
getting EM " ex) return em
public void addItem(Item item)
throws InvalidItemException EntityManage
r em getEntityManager() try ...
13Application-Managed EM
- First obtain an EntityManagerFactory using
_at_PersistenceUnit annotation
- EMFs are thread safe
- Then, inside the method, call createEntityManger()
on the EMF instance
- Lifecyle managed by you
- CreateEntityManager(), isOpen(),
joinTransaction(), close().
14Application-Managed EM
_at_PersistenceUnit private EntityManagerFactory
emf _at_Resource UserTransaction utx public v
oid addItem(Item item) EntityManager em emf.
createEntityManager() try utx.begin()
em.joinTransaction() em.persist(item)
utx.commit() ... finally em.cl
ose()
15DEMO
16JPA Programming Model
- Web-only Use
- Primary Keys
- Named Queries
- Model Facade
17Primary Keys
- All persistent entities are required to have a
primary key
- The key may be simple or composite
18Simple Primary Keys
- Field (property) mapped to the primary key of the
table.
- Denoted with the _at_Id annotation
_at_Id private int itemID
19Composite Primary Keys
- Represented by a composite key class
- Defined with _at_EmbeddedId or _at_IdClass
- Key class must
- Be serializable
- Define equals() and hashCode()
- If using _at_EmbeddedId, be annotated with
_at_Embeddable
20Composite Primary Keys
_at_Embeddable public class ContactPK implements Ser
ializable private String firstname
private String lastname
...
21Composite Primary Keys
_at_Entity public class Contact implements Serializa
ble / EmbeddedId primary key fi
eld / _at_EmbeddedId protected Conta
ctPK contactPK ...
22DEMO
23Primary Key Generation
- Generation Options
- Application
- Persistence Provider
- Database
24Application Key Generation
- Use inherently primary data (e.g. Passport )
- Use a table of sequence numbers
- Developer writes generation logic
- Use System.currentTimeMillis()
- Be careful in a clustered environment
- Advantage of knowing the key before it's stored.
- Useful when needed as a foreign key elsewhere
25Auto Key Generation
- Provided by the persistence provider or the
database
- Let the container / DB do the work.
- Use _at_GeneratedValue along with _at_Id
- Optionally specify a strategy and id generator
26Auto Key Generation
- Strategies
- AUTO (Default)
- Decided by the persistence provider. Not
necessarily portable. TopLink uses TABLE.
- TABLE
- Values are assigned based on an underlying DB
table, not DB specific features.
- SEQUENCE
- Will not be portable if DB doesn't support
Sequences.
- IDENTITY
- Will not be portable if DB doesn't support
IDENTITY column type.
27Auto Key Generation
- In a clustered environment
- TABLE and SEQUENCE
- All dependant on the underlying persistence
provider.
- Verify how your provider handles these generation
types in a clustered environment.
- For example, TopLink Essentials does not support
coordinated caching, but Oracle TopLink does.
- IDENTITY
- The database generates the key w/out the
persistence provider.
28Auto Key Generation
- If Strategy is TABLE or SEQUENCE, you can also
specify an ID generator using
- _at_TableGenerator
- for TABLE stragegy
- _at_SequenceGenerator
- For SEQUENCE strategy
29Auto Key Generation
_at_TableGenerator
_at_GeneratedValue( strategyGenerationType.TA
BLE, generator"ID_GEN") _at_TableGenerator
(name"ID_GEN", table"ID_GEN",
pkColumnName"GEN_KEY",
valueColumnName"GEN_VALUE",
pkColumnValue"ITEM_ID")
_at_Id private int itemID ...
30DEMO
31Key Maintainence
- All entities require a key
- Keys should not be modified
- If necessary, remove and add the entity
- Keep in mind referential integrity
32JPA Programming Model
- Web-only Use
- Primary Keys
- Named Queries
- Model Facade
33Named Queries
- Clean up SQL scattered throughout your code
- Generally precompiled by the persistence
provider
- Helps find bugs before deployment
- Thread-safe
- Can only be defined on entities
- Used for both native SQL and JPA query language
34Named Queries
- Define the query on the entity
_at_NamedQuery( name"Item.getItemsPricedGreaterTh
an", query"SELECT i FROM Item i WHERE i.listPr
ice price" ) _at_Entity public class
Item implements java.io.Serializable ...
35Named Queries
Client Usage
public List getExpensiveItems()
EntityManager em emf.createEntityManager
() Query query em.createN
amedQuery("Item.getItemsPricedGreaterThan")
query.setParameter("price",300)
List items query.getResultList()
return items
36DEMO
37Named Queries
_at_NamedQueries
_at_NamedQueries( _at_NamedQuery( name"It
em.getItemsPricedGreaterThan",
query"SELECT i FROM Item i WHERE
i.listPrice price" ), _at_Name
dQuery( name"Item.getItemsPricedLessThan",
query"SELECT i FROM Item i WHERE
i.listPrice
38DEMO
39JPA Programming Model
- Web-only Use
- Primary Keys
- Named Queries
- Model Facade
40Model Facade
- The Facade pattern helps shield your client code
from the various APIs associated with a growing
lists of entity classes
- It provides a single interface for operations on
a set of entities.
- No worries about API details, persistence
mechanisms, transaction managers, etc.
- Code becomes more loosely-coupled (and easier to
maintain)
41Client Code Before Model Facade
_at_PersistenceUnit(unitName"CatalogPu")
private EntityManagerFactory emf
_at_Resource UserTransaction utx
... Item item new Item()
item.setName("Wild Cat")
EntityManager em emf.createEnt
ityManager() try utx.begin
() em.joinTransaction()
em.persist(item) utx.commit()
catch(Exception exe) System.
err.println("Error persisting item "exe)
try utx.rollback()
catch (Exception e) throw new Ru
ntimeException("Error persisting item "
e.getMessage(), e)
throw new RuntimeException("Error
persisting item " exe.getMe
ssage(), exe) finally e
m.close()
42Client Code After Model Facade
CatalogFacade cf new CatalogFacade()
cf.addItem(Wild Cat)
43Question
Where do you code your facade?
44Answers
POJO DI is not available Web component (servlet,
backing bean) Good choice for web-only apps Ses
sion Bean An EJB Container is required But its s
ervices are also available
45Web Component Facade
- Useful for web-only archictectures
- See sample web-only-app
- CatalogFacade
- CatalogServlet (the client)
- Implementing ServletContextListener allows it to
use annotations
- Must manage entity manger lifecycle and
transactions (see Web-Only)
46Web Component Facade
public class CatalogFacade implements
ServletContextListener _at_PersistenceUnit(u
nitName"CatalogPu") private EntityManagerFac
tory emf _at_Resource UserTransaction utx
public CatalogFacade() public
void contextInitialized(ServletContextEvent sce)
ServletContext context sce.getServlet
Context() context.setAttribute("CatalogF
acade", this)
47Web Component Facade
Client Use
public class CatalogServlet extends HttpServlet
private CatalogFacade cf private Serv
letContext context public void init(Se
rvletConfig config) throws ServletException
context config.getServletConte
xt() cf (CatalogFacade)context.getAttr
ibute("CatalogFacade") public v
oid destroy() cf null
48Session Bean Facade
- Container handles
- Facade lifecyle
- Entity Manager lifecycle
- Transactions
- Much cleaner code
- Dependency on EJB container.
49Session Bean Facade
We don't have to worry about initialization code
_at_Stateless public class CatalogFacadeBean impleme
nts CatalogFacade _at_PersistenceContext(uni
tName"CatalogPu")
private EntityManager em
We get transaction management for free
50Session Bean Facade
Client Use
public class CatalogServlet extends HttpServlet
_at_EJB(name"CatalogFacadeBean") private Catal
ogFacade cf
51References
- Java BluePrints
- https//blueprints.dev.java.net
- NetBeans
- Blog
- Brian http//weblogs.java.net/blog/bleonard/
52Summary
- Java EE 5 introduces JPA
- JPA is simply powerful
- JPA does not required an EJB 3 container
53- Use JPA to properly de-couple your application's
persistence needs from the underlying provider.
54QA
55- Thank you for your attention!