Java EE 5 BluePrints - PowerPoint PPT Presentation

1 / 55
About This Presentation
Title:

Java EE 5 BluePrints

Description:

11 - 15 DECEMBER ANTWERP BELGIUM. www.javapolis.com. Java EE 5 BluePrints ... 11 - 15 DECEMBER ANTWERP BELGIUM. www.javapolis.com. DEMO. JPA Programming Model ... – PowerPoint PPT presentation

Number of Views:324
Avg rating:3.0/5.0
Slides: 56
Provided by: netb
Category:

less

Transcript and Presenter's Notes

Title: Java EE 5 BluePrints


1
(No Transcript)
2
Java 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
3
Overall Presentation Goal
Learn Best Practices for using the Java
Persistence API

4
Speakers 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.

5
Java EE 5 Goal
Make it easier to develop Java EE applications
Especially when first getting started with Java
EE
6
JPA Programming Model
  • Web-only Use
  • Primary Keys
  • Named Queries
  • Model Facade

7
JPA Programming Model
  • Web-only Use
  • Primary Keys
  • Named Queries
  • Model Facade

8
A Web-Only App
  • Doesn't have EJBs
  • Runs in a Java EE 5 Container
  • Servlet 2.5

9
Entity Manager Decision
  • Container Managed
  • Application Managed

10
Web-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

11
Container-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

12
Container-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 ...
13
Application-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().

14
Application-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()
15
DEMO
16
JPA Programming Model
  • Web-only Use
  • Primary Keys
  • Named Queries
  • Model Facade

17
Primary Keys
  • All persistent entities are required to have a
    primary key
  • The key may be simple or composite

18
Simple Primary Keys
  • Field (property) mapped to the primary key of the
    table.
  • Denoted with the _at_Id annotation

_at_Id private int itemID
19
Composite 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

20
Composite Primary Keys
_at_Embeddable public class ContactPK implements Ser
ializable private String firstname
private String lastname
...
21
Composite Primary Keys
_at_Entity public class Contact implements Serializa
ble / EmbeddedId primary key fi
eld / _at_EmbeddedId protected Conta
ctPK contactPK ...
22
DEMO
23
Primary Key Generation
  • Generation Options
  • Application
  • Persistence Provider
  • Database

24
Application 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

25
Auto 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

26
Auto 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.

27
Auto 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.

28
Auto 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

29
Auto 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 ...
30
DEMO
31
Key Maintainence
  • All entities require a key
  • Keys should not be modified
  • If necessary, remove and add the entity
  • Keep in mind referential integrity

32
JPA Programming Model
  • Web-only Use
  • Primary Keys
  • Named Queries
  • Model Facade

33
Named 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

34
Named 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 ...
35
Named 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
36
DEMO
37
Named 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 38
DEMO
39
JPA Programming Model
  • Web-only Use
  • Primary Keys
  • Named Queries
  • Model Facade

40
Model 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)

41
Client 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()
42
Client Code After Model Facade
CatalogFacade cf new CatalogFacade()
cf.addItem(Wild Cat)
43
Question
Where do you code your facade?
44
Answers
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
45
Web 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)

46
Web 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)
47
Web 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
48
Session Bean Facade
  • Container handles
  • Facade lifecyle
  • Entity Manager lifecycle
  • Transactions
  • Much cleaner code
  • Dependency on EJB container.

49
Session 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
50
Session Bean Facade
Client Use
public class CatalogServlet extends HttpServlet
_at_EJB(name"CatalogFacadeBean") private Catal
ogFacade cf
51
References
  • Java BluePrints
  • https//blueprints.dev.java.net
  • NetBeans
  • Blog
  • Brian http//weblogs.java.net/blog/bleonard/

52
Summary
  • 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.

54
QA
55
  • Thank you for your attention!
Write a Comment
User Comments (0)
About PowerShow.com