EJB 3.0 Persistence API - PowerPoint PPT Presentation

1 / 40
About This Presentation
Title:

EJB 3.0 Persistence API

Description:

Easy to facilitate by IDEs. Productive in use: Configuration by Exception' 12 ... IDEs: JDeveloper 10.1.3, DALI for Eclipse. 14. EJB 3.0 Persistence Workshop ... – PowerPoint PPT presentation

Number of Views:485
Avg rating:3.0/5.0
Slides: 41
Provided by: LucasJ6
Category:
Tags: api | ejb | ides | persistence

less

Transcript and Presenter's Notes

Title: EJB 3.0 Persistence API


1
EJB 3.0 Persistence API
  • Workshop
  • Dinsdag 9 mei 2006

empno name salary
empno name salary
2
Agenda
  • History of Object Relational Mapping
  • EJB 2.x and before
  • Birth of EJB 3.0 Persistence (JSR-220)
  • The essence of the EJB 3.0 Persistence API
  • Mapping
  • EJB QL and Query Interface
  • EntityManager and Persistency Services
  • The Sample Application AMIS Library System
  • Getting Started using the GlassFish RI
  • Download and install
  • Mapping annotations
  • Your first EJB 3.0 Persistence API based program

3
Agenda (2)
  • Data Manipulation via EntityManager
  • Create and Insert
  • Merge and Update
  • Remove and Delete
  • Advanced Mapping
  • Foreign Keys, Intersections and Collections
  • Versions and optimistic locking
  • Auto-increment or database sequences
  • EBJ Query Language (EJB QL)
  • Next Steps
  • Leverage a vendor specific implementation such as
    Kodo, TopLink or Hibernate
  • Use Cache, Stored Procedures

4
History of Object Relational Mapping
  • Java applications and Relational databases
  • Objects vs. Tables
  • Volatile (Memory) vs. Permanent or Persistence
    (File)
  • Required Services
  • Query
  • Save (Insert and Update)
  • Remove (Delete)
  • And maybe
  • Security
  • Locking Integrity
  • Performance Indexes
  • Stored Procedures
  • JDBC

empno name salary
empno name salary
5
History of Object Relational Mapping (2)
  • JDBC
  • a specification of an API (interface)
  • Database Driver provides the database specific
    implementation
  • Downsides to JDBC
  • SQL Embedded in Java Code
  • Java developers need to learn SQL as well
  • JDBC means raw SQL means database specific means
    Java application less portable
  • JDBC has no facilities for caching, locking or
    refresh of data
  • JDBC statements are awkward the resource
    management and exception handling may take 80
    or more of the codeonly 20 is the actual,
    functional work
  • Lots of repetitions of simple operations
  • Manual OO/R translation JDBC does not speak in
    Domain Objects

empno name salary
empno name salary
6
History of Object Relational Mapping (3)
  • Alternative solutions
  • Toplink (The Object People 1994, 2000 WebGain,
    2002 Oracle)
  • Hibernate (JBoss group)
  • BC4J aka ADF Business Components (Oracle)
  • IBATIS, Castor, OJB,
  • JDO (Java Data Objects) JSR 12, 2002 e.g.
    Kodo
  • JDO 2.0 (JSR-243) blocked early 2005 by IBM, BEA
    and Oracle
  • Spring Persistence
  • Mapping
  • Table gt Class
  • Column gt Property
  • Foreign Key gt Reference and Collection
  • Facilities lock, cache, refreshbulk dml, stored
    procedures, sequences

empno name salary
empno name salary
7
JDBC and ORM Frameworks
Plain JDBC
ORM Framework (TopLink etc.)
Application Code OO Query Language OO DML
Calls
Application Code SQL statements DIY O/R
Mapping
ORM Framework
Plain JDBC
OO Query API DML Services OO/R Mapping cache lock
refresh/synch
no mapping no cache no lock no refresh
xml
SQL
SQL
JDBC
Java Virtual Machine
JDBC
RDBMS
8
History of Object Relational Mapping (4)
  • 1997 Enterprise Java Beans
  • Note J2EE was born in 1999!
  • EJB 2.1 is in J2EE 1.4, released early 2004
  • Flavors
  • Stateless, Stateful
  • EntityBean, Session Bean, (MessageDrivenBean)
  • BMP, CMP (Container Managed Persistence)
  • Local, remote (EJB 2.1)
  • Distributed application
  • Remote (RMI) calls to EJBs

9
History of Object Relational Mapping (5)
  • Enterprise Java Beans what went wrong
  • Not as portable
  • Not as performant
  • Not as productive
  • Not as simple
  • Not as functionally rich
  • e.g. EJB QL 2.1 has no Date type, no sub queries,
    no group by or having, almost no functions, no
    access to native SQL)
  • Not as (unit)testable
  • Not as elegant
  • Not as cheap
  • .

10
Birth of EJB 3.0 Persistence API (JSR-220)
  • Announcement October 2004
  • POJO based API for standardized Persistence
  • Both in (EJB-) container and outside (J2SE)
  • Reduced Complexity
  • Use of Annotations
  • Configuration by Exception
  • Open SourceRI GlassFish
  • SUN App
  • Toplink

11
The promise of EJB 3.0 Persistence API
  • Industry wide standard for ORM
  • Developers need to learn a single approach
  • Applications become portable between ORM
    Frameworks
  • ORM for Enterprise level EJB Containers as well
    as J2SE and Web applications
  • Including Swing Client, JSP/Servlet Web
    applications etc.
  • No legacy to work from built from a clean slate
  • And drawing from years of experience from the
    major vendors
  • A simple, elegant and functionally rich interface
  • Easy to learn for developers
  • Easy to facilitate by IDEs
  • Productive in use Configuration by Exception

12
Java Community Process - JSR 220
13
Support from major vendors
  • Sun
  • JBoss/Hibernate
  • BEA/Kodo (previously SolarMetric)
  • Caucho/Resin (Amber)
  • Oracle/TopLink
  • Production May 2006
  • Final Specification -
  • Already implementations Hibernate 3.0, TopLink
    10.1.3, Oracle 10gAS 10.1.3, Kodo 4
  • 20 april 2006 Glassfish Stand Alone Persistence
    Library
  • IDEs JDeveloper 10.1.3, DALI for Eclipse

14
Mapping through Annotationsand Configuration by
Exception
  • Mapping
  • Associating Classes with tables, Properties with
    columns and Object References with foreign keys
  • EJB 3.0 Persistence API
  • No separate XML configurationfiles for the
    mapping
  • Instead, use Java 5.0 Meta DataAnnotations in
    the Class definition
  • _at_Entity
  • _at_Table(name)
  • _at_Column(name)
  • _at_Id

15
Core in EJB 3.0 Persistence API The
EntityManager
  • Provides Persistence Services for Entities
  • Persist, Merge, Remove, Query, Find, Flush,
    Refresh
  • Each Service is used in the context of a Class or
    a POJO
  • Only Classes that are annotated with _at_Entity
  • The EntityManager interprets the Mapping
    Annotations to translate a Class or POJO Service
    Request into a Table oriented SQL statement
  • entityManager.persist(pojo) ? INSERT INTO
    POJO_TABLE
  • The EntityManager gets the Database Connection
  • From the file persistence.xml (in J2SE)
  • Through Injection by the Container
  • _at_Inject
  • private EntityManager entityManager

16
ORM with EJB 3.0 Persistence API
MyApp em createEntityManager() Employee e
new Employee() e.setEmpno(new Long(10)) e.setNam
e(Lucas) em.persist(e) Employee e2 em.find
( Employee.class , new Long(40))
EntityManagerFactory
persistence.xml
Employee
Employee
Empno40 nameJohn salary2312
empno10 nameLucas Salary
Java Virtual Machine
SELECT
JDBC
INSERT
RDBMS
17
Persistence.xml
  • Only needed outside the EJB container
  • Located in classes/META-INF directory or in a jar
  • Contains the DataSource or Connection, a list of
    entities and a reference to the actual EJB 3.0
    Persistence APIImplementations Factory Class

18
The ALS Workshop Application
19
Creating the Publisher Entity
20
Creating Persistence.xml
21
Talking to the EntityManager
22
First Practice Getting Started with EJB 3.0
Persistence using the GlassFish Reference
Implementation
  • Download and install GlassFish
  • Create Entities POJOs with Annotations
  • Create persistence.xml
  • With database connection and entities
  • Create a LibraryService object
  • That provides services and encapsulates the EJB
    3.0 Persistence API
  • Create a LibraryClient object
  • That leverages the LibraryService services
  • Run the LibraryClient
  • Get the first results from the database

23
Data Manipulation
MyApp em createEntityManager() Employee e
new Employee() e.setEmpno(new Long(10)) e.setNam
e(Lucas) em.persist(e)
EntityManagerFactory
persistence.xml
Employee
Employee
Empno40 nameJohn salary2312
empno10 nameLucas Salary
Java Virtual Machine
SELECT
JDBC
INSERT
24
EntityManager API Data Manipulation Facilities
  • Data Manipulation Operations
  • Persist() gt INSERT
  • Merge() gt UPDATE
  • Remove() gt DELETE
  • They all take an Entity as input parameter
  • Merge also returns an Entity
  • Can only be executed inside
  • EntityManager also provides getTransaction()
  • An EntityTransaction has few operations most
    notable begin(), commit() and rollback()
  • EntityManager does not provide access to JDBC
    Connection object!
  • Flush() can be used to force the execution of the
    DML SQL statement to the database
  • Without flush(), there is no guarantee about when
    the SQL is executed (at the latest at commit
    time)

25
Example of Persisting and Changing Entities
26
Second Practice - Basic Data Manipulation through
the EJB 3.0 Persistence API
  • Create a savePublisher() method in the
    LibraryService
  • Invoke it from the LibraryClient to make your new
    Publisher objects permanent in the database
  • Change one of the freshly created Publisher
    objects
  • And make the changes permanent
  • Remove the new Publishers
  • Handle the Transactions
  • And learn a little about attached/detached
    entities

27
Advanced MappingsRelationships
  • Create new entity Book
  • Mapped to ALS_BOOKS
  • Create a Publisher reference in Book
  • And a books reference in Publisher
  • And annotate!

28
ManyToOne annotationReference to a single
(master) entity
29
Following the ManyToOne Reference
30
OneToManyParent to its children
31
ManyToManyResolution of Intersection Entities
32
ManyToManyResolution of Intersection Entities
33
Primary Key generation
  • EJB 3.0 Persistence supports several ID
    generation policies
  • Sequence
  • Identity column
  • Table based sequence generator

34
Optimistic Locking using a Version attribute
  • Optimistic locking means
  • Do not lock in advance the lock is probably not
    required for most records you retrieve
  • When sending the changes to the database, verify
    whether no one else has updated since you
    retrieved the data
  • If someone did, do not update otherwise you
    would overwrite the changes!!
  • EJB 3.0 Persistence can do optimistic locking
    automatically
  • Using a numeric or date/timestamp type column

35
Optimistic Locking
  • Add a VERSION column to the table
  • If you have a LAST_MODIFIED column you can use
    that one as well
  • Add an attribute for that column to your Entity
    and annotate with _at_Version
  • When you create or update the entity,
    theEntityManager will
  • maintain the versioncolumn and
  • check forchanges by other usersupdate where
    version ltthe old version valuegt

36
EJB QL The Query Language
  • Queries in terms of Entities and Attributes
  • And NativeQuery as escape
  • Results also in terms of Entities and normal
    Objects
  • Therefore
  • Portable across Databases
  • No need for the developer to know SQL (!?)
  • Queries more functional than technical
  • However
  • EJB QL is not necessarily much simpler than SQL
  • NativeQuery breaks portability anyway

37
EJB QL How to perform a Query
  • Get a Query Instance from the EntityManager
  • Specify the Query text or use a Named Query
  • Specify the parameters (if they are used)
  • Execute the query
  • Process the result set

38
Queries can .
  • Be Named and predefined using Annotations
  • Include Named Parameters
  • Return multiple Entity-types
  • For example Publisher and Author
  • Execute Native SQL
  • Using Oracle Analytical Functions, PL/SQL
    interaction, Scalar Subqueries, In Line Views,
    Connect By etc.
  • Perform Bulk Update and Bulk Delete
  • NOT Invoke Stored Procedures!

39
One more EJB QL example
40
IDE Suport
  • JDeveloper
  • Generate Entities from Tables
  • Eclipse Dali plugin
  • Wizard for editing annotations
Write a Comment
User Comments (0)
About PowerShow.com