EJB 3.0

About This Presentation
Title:

EJB 3.0

Description:

Open Source Projects. JBoss Application Server (#1 Market Share) Hibernate. JGroups ... Professional Open Source. JDK 5.0 Annotations. XDoclet like metadata, ... – PowerPoint PPT presentation

Number of Views:912
Avg rating:3.0/5.0
Slides: 67
Provided by: Me3

less

Transcript and Presenter's Notes

Title: EJB 3.0


1
EJB 3.0
  • Ease of use

2
JBoss Inc.
  • Open Source Projects
  • JBoss Application Server (1 Market Share)
  • Hibernate
  • JGroups
  • JBoss jBPM
  • JBoss AOP
  • JBoss Portal
  • JBoss Mail
  • JBoss Eclipse IDE
  • Javassist
  • Tomcat
  • JCP Committees
  • Executive
  • EJB 3.0
  • Web Services
  • J2EE 1.5
  • JBI

3
JBoss Inc.
  • Services
  • Training
  • Coming to a city near you
  • Onsite on demand
  • 24x7 Support
  • Consulting
  • ISV/OEM Support Partnerships
  • 10 Discount for JUG members on all training
  • EJB 3.0 training coming soon

4
Overall Agenda
  • Goals of EJB 3.0
  • JDK 5.0 Annotations
  • Session Beans
  • Entity Beans
  • Interceptors
  • Callback Listeners

5
Goals of EJB 3.0
  • EJB 2.1 is too noisy
  • Too many interfaces to implement
  • XML Hell too many complex deployment
    descriptors
  • API is too verbose
  • API too complicated in general
  • Simplify the EJB programming model
  • Focus on ease of use
  • Facilitate Test Driven Development
  • Make it simpler for average developer
  • Increase developer base

6
JDK 5.0 Annotations
  • XDoclet like metadata, C-like metatags
  • Typesafe, compiler-checked
  • Syntax you can add to the Java language
  • Metadata you can attach to class, method, field,
    constructor, or parameter
  • Metadata is compiled into class file
  • Available at compile time and/or runtime
  • EJB 3.0 makes extensive use of annotations to
    replace XML

7
JDK 5.0 Annotations
public _at_interface MyMetadata
String value() default hello
----------------------------------------------
-------------- import org.acme.MyMetadata _at_My
Metadata(stuff) public class MyClass
_at_MyMetadata public void someMethod()
8
Session Beans
  • Compare EJB 2.1 vs. EJB 3.0

9
EJB 2.1 Requirements
  • Home interface
  • Remote/Local interface
  • Bean class must implement javax.ejb.SessionBean
  • XML Deployment descriptor

10
EJB 2.1 Required Interfaces
  • Homes for stateless beans unnecessary
  • Remote interface must inherit from EJBObject
  • Remote methods must throw RemoteException
  • Dependency on RMI

public interface CalculatorHome extends
javax.ejb.EJBHome public Calculator create() t
hrows CreateException public interface Calc
ulator extends EJBObject Public int add(int x,
int y) throws RemoteException
Public int subtract(int x, int y) throws
RemoteException
11
EJB 2.1 Bean class requirements
  • Must extend verbose javax.ejb.SessionBean
  • Unnecessary and verbose callback methods

public class CalculatorBean implements
javax.ejb.Sessionbean private SessionContext ct
x public void setSessionContext(SessionContext c
tx) this.ctx ctx public void ejbCreate()
public void ejbRemove() public void ejbA
ctivate() public void ejbPassivate() pub
lic int add(int x, int y) return x y p
ublic int subtract(int x, int y)
return x y
12
EJB 2.1 XML Deployment Descriptor
CalculatorBean omeorg.acme.CalculatorHome
org.acme.CalculatorBean
org.acme.CalculatorRemote
Stateless
Container
.
13
EJB 3.0 Goals
  • Remove unnecessary interfaces
  • Remove unnecessary callbacks
  • Make deployment descriptors optional
  • Make beans pojo-like
  • Use default values where they make sense

14
Required Interfaces
  • Homeless
  • Methods dont throw RemoteException
  • No verbose interface implementations

_at_Remote public interface Calculator
public int add(int x, int y) public int subtract
(int x, int y) _at_Stateless Public class Calcul
atorBean implements Calculator
public int add(int x, int y)
return x y public int subtract(int x, int
y) Return x y
15
EJB 3.0 XML Deployment Descriptor
16
Stateful Beans
  • Still homeless
  • Created as they are looked up
  • _at_Remove replaces EJBObject.remove
  • Stateful bean is removed after method called

_at_Remote public interface ShoppingCart
public void addItem(int prodId, int quantity)
public void checkout() _at_Stateful public cla
ss ShoppingCartBean implements ShoppingCart
_at_Remove public void checkout()

17
MDBs
  • Just implements MessageListner
  • XML turns to annotations
  • Not-much new. Suggestions?

_at_MessageDriven( activationActivationSp
ecAttribute(namedestinationType,
valuejavax.jms.queue)) public class EmailBean
implements MessageListener void
onMessage(Message msg) public int add(int x,
int y) return x y
18
Transactions and Security
_at_Stateful public class ShoppingCartBean implemen
ts ShoppingCart _at_Remove _at_Transa
ctionAttribute(REQUIRED) _at_MethodPermission(vali
d_customer) public void checkout()

19
EJB 3.0 Dependency Injection
  • Bean class specifies dependencies instead of
    lookup
  • Facilitates Test Driven Development
  • Possible to test EJBs outside of container

_at_Stateful public class ShoppingCartBean
implements ShoppingCart _at_Inject private Sessi
onContext ctx _at_EJB(nameCreditProcessorEJB)
private CreditCardProcessor processor privat
e DataSource jdbc _at_Resource(jndiNamejava/De
faultDS) public void setDataSource(DataSource db
) this.jdbc db
20
EJB 3.0 Callbacks on demand
  • Callback methods still available
  • Annotate on an as-needed basis

_at_Stateless public class FacadeBean implements
Facade _at_EjbTimeout void licenseExpired(Timer t)
// committee is leaning towards this
_at_PostCreate public void initialize() // curre
ntly in public draft
21
EJB 3.0 Deployment Descriptor
  • Believe it or not, people like XML deployment
    descriptors
  • Externalize configuration
  • Externalize system architecture
  • Although not in draft, XML DDs are optional
  • Replace annotations with XML and you get pure
    POJOs

22
EJB 3.0 Deployment Descriptors
_at_Remote public interface ShoppingCart
public void addItem(int prodId, int quantity)
public void checkout() _at_Stateful public class
ShoppingCartBean implements ShoppingCart
_at_Inject private EntityManager
manager _at_Remove
_at_TransactionAttribute(REQUIRED)
_at_MethodPermission(valid_customer)
public void checkout()
23
EJB 3.0 Deployment Descriptors
public interface ShoppingCart
public void addItem(int prodId, int quantity)
public void checkout() public class Shopp
ingCartBean implements ShoppingCart
private EntityManager manager
public void checkout()

24
Entity Beans
  • POJO based persistence

25
Goals of Entity Beans
  • Same goals as session beans
  • Fewer interfaces, optional XML DDs, etc.
  • No required interfaces or subclassing
  • Plain Java based
  • Allow new()
  • Provide full Object/Relational mapping
  • Supports Inheritance
  • Expanded EJBQL
  • Fully featured
  • Parallel SQL
  • Polymorphic Queries

26
Defining Entity Beans
  • Full Object/Relational Database Mapping

27
EJB 3.0 Entity Beans
  • O/R Mapping Metadata as annotations
  • Table mappings, _at_Table, _at_SecondaryTable
  • Column mappings, _at_Column, _at_JoinColumn
  • Relationships, _at_ManyToOne, _at_OneToOne, _at_OneToMany,
    _at_ManyToMany
  • Multi-Table mappings, _at_SecondaryTable
  • Embedded objects, _at_Dependent
  • Inheritance, _at_Inheritance, _at_DiscriminatorColumn
  • Identifier Version properties, _at_Id, _at_Version

28
Entity Annotations
_at_Entity _at_Table(nameAUCTION_ITEM) public class
Item private long id private String
description private String productName
private Set bids new HashSet()
private User seller _at_Id(generateGenera
torType.AUTO) _at_Column(nameITEM_ID) pu
blic long getId() return id
public void setId(long id)
this.id id .
relational table declaration
auto-key generation
29
Entity Annotations
_at_Entity _at_Table(nameAUCTION_ITEM) public class
Item private long id private String
description private String productName
private Set bids new HashSet()
private User seller _at_Id(generateGenera
torType.AUTO) _at_Column(nameITEM_ID) pu
blic long getId() return id
public void setId(long id)
this.id id .
create table AUCTION_ITEM ( ITEM_ID Number, DES
C varchar(255), ProductName varchar(255), USER_I
D Number
)
30
Entity Annotations
_at_Entity _at_Table(nameAUCTION_ITEM) public class
Item private long id private String
description private String productName
private Set bids new HashSet()
private Owner owner _at_Id(generateGenera
torType.AUTO) _at_Column(nameITEM_ID) pu
blic long getId() return id
public void setId(long id)
this.id id .
create table AUCTION_ITEM ( ITEM_ID Number, DES
C varchar(500), ProductName varchar(255), OWNER_
ID Number
)
31
Entity Annotations
_at_Column(nameDESC, length500) publ
ic String getDescription() return desc
ription public void setDescription(S
tring desc) this.description desc
public String
getProductName() return productName
protected void setProductName(String
name) this.productName name

column mapping
intuitive defaults
32
Entity Annotations
_at_Column(nameDESC, nullablefalse, lengt
h500) public String getDescription()
return description public void
setDescription(String desc)
this.description desc
public String getProductName(
) return productName pro
tected void setProductName(String name)
this.productName name

create table AUCTION_ITEM ( ITEM_ID Number, DES
C varchar(500), ProductName varchar(255), OWNER_
ID Number
)
33
Relationships
  • Relationships,
  • _at_ManyToOne, _at_OneToOne, _at_OneToMany, _at_ManyToMany
  • Supports lazy and eager loading of relationships
  • Cascades delete, create, and merge
  • No CMR You must manage the relationships
    somewhat.

34
Entity Relationships
lazy/eager loading
_at_OneToOne(fetchLAZY) _at_Column(nameOWNER_I
D) public Owner getOwner() retur
n owner protected void setOwner(Ow
ner owner) this.owner owner
_at_OneToMany(cascadeALL) _at_JoinColumn(n
ameITEM_ID) protected Set getBids()
return bids protected voi
d setBids(Set bids) this.bids b
ids
various cascade types
35
Entity Relationships
_at_OneToOne(fetchLAZY) _at_Column(nameOWNER_I
D) public Owner getOwner() retur
n owner protected void setOwner(Ow
ner user) this.owner owner
_at_OneToMany(cascadeALL)
_at_JoinColumn(nameITEM_ID) protected Set getBids() return bids
protected void setBids(Set bids)
this.bids bids
create table AUCTION_ITEM ( ITEM_ID Number, DES
C varchar(255), ProductName varchar(255), OWNER_
ID Number ) create table BID ( ITEM_ID
Number )
36
Multi-Table
  • Multi-Table Mappings,
  • Entity can be stored in one or more tables
  • _at_SecondaryTables, _at_SecondaryTable

37
Multi-table Mappiings
_at_Entity _at_Table(nameOWNER) _at_SecondaryTable(nam
eADDRESS join
_at_JoinColumn(nameADDR_ID))
public class Owner private long id pr
ivate String name private String street
private String city private String state
_at_Id(generateGeneratorType.AUTO)
_at_Column(nameOWNER_ID) public long getId()
return id public void se
tId(long id) this.id id
.
create table OWNER ( OWNER_ID Number, NAME varc
har(255), ) create table ADDRESS ( ADDR_ID
Number, STREET varchar(255), CITY varchar(255),
STATE varchar(255) )
38
Multi-Table Mappings
_at_Column(nameSTREET, secondaryTableADD
RESS) public String getStreet()
return street public void setStreet(
String street) this.street street
_at_Column(nameCITY,
secondaryTableADDRESS) public String getCi
ty() return city protect
ed void setCity(String city)
this.city city
create table OWNER ( OWNER_ID Number, NAME varc
har(255), ) create table ADDRESS ( ADDR_ID
Number, STREET varchar(255), CITY varchar(255),
STATE varchar(255) )
39
Embedded Objects
  • Embedded Objects
  • Aggregated objects whose properties can be
    mapped
  • _at_Dependent, _at_DependentObject

40
Embedded Objects
_at_Entity _at_Table(nameOWNER) public class Owner
private long id private String name
private Address address
_at_Id(generateGeneratorType.AUTO)
_at_Column(nameCUST_ID) public long getId(
) return id public void
setId(long id) this.id id
_at_Column(nameNAME) public String getNam
e() .
_at_DependentObject Public class Address priva
te String street private String city pri
vate String state public String getStreet(
) return street public void
setStreet(String street) this.street st
reet public String getCity()
return city
41
Entity Annotations
_at_Dependent( _at_DependentAttribute(na
mestreet, _at_Column(nameSTREET)),
_at_DependentAttribute(namecity,
_at_Column(nameCITY)), _at_DependentAttribut
e(namestate, _at_Column(nameSTATE)))
public Address getAddress()
return address public void set
Address(Address address) this.address
address
42
Interacting With Entity Bean
  • Plain Java Objects

43
Entity Manager
  • Entities created as any plain Java object
  • Customer cust new Customer()
  • Plain Java objects and homeless
  • Can be detached and reattached to container
  • Can be serialized to remote client
  • Remote client can perform updates on local copy
  • Copy can be sent back to server and merged back
    in
  • Persisted by the EntityManager service
  • All access through this service
  • Creation, retrieval, removal, and merging
  • Analogous to Hibernate Session

44
Create the objects
  • Create the entities like you would any other
    object
  • Allocate entire object graph like any other Java
    code

Item item new Item() item.setDescription(Ore
illys EJB 4th Edition) item.setProductName(EJ
B 2.1 Book) Owner bill new Owner() bill.
setName(Bill) item.setOwner(bill) Bid bid
new Bid() HashSet bids new HashSet()
bids.add(bid) item.setBids(bids)
45
Entity Manager
  • All entities persisted by the EntityManager
    service
  • All access through this service
  • Creation, retrieval, removal, and merging
  • Analogous to Hibernate Session
  • Injected with dependency injection

46
EntityManager
_at_Stateless public class ItemDAOImpl implements
ItemDAORemote _at_Inject private EntityManag
er em public long create(Item item)
em.create(item) return item.get
Id() public Item findById(long id)
return (Item) em.find(Item.class, id)
public void merge(Item item)
em.merge(item)
Inject the EntityManager service
47
EntityManager
_at_Stateless public class ItemDAOImpl implements
ItemDAORemote _at_Inject private EntityManag
er em public long create(Item item)
em.create(item) return item.get
Id() public Item findById(long id)
return (Item) em.find(Item.class, id)
public void merge(Item item)
em.merge(item)
Item allocated remotely If cascade CREATE, enti
re object graph inserted into storage

48
EntityManager
_at_Stateless public class ItemDAOImpl implements
ItemDAORemote _at_Inject private EntityManag
er em public long create(Item item)
em.create(item) return item.get
Id() public Item findById(long id)
return (Item) em.find(Item.class, id)
public void merge(Item item)
em.merge(item)
Item found with primary key Detached from persi
stent storage at tx completion
Can be serialized like any other object

49
EntityManager
_at_Stateless public class ItemDAOImpl implements
ItemDAORemote _at_Inject private EntityManag
er em public long create(Item item)
em.create(item) return item.get
Id() public Item findById(long id)
return (Item) em.find(Item.class, id)
public void merge(Item item)
em.merge(item)
Item can be updated remotely and merged back to
persistent storage Item instance is reattached t
o storage with merge() call

50
Query API
  • Queries may be expressed as EJBQL strings
  • Embedded in code
  • Externalized to metadata (named queries)
  • Invoke via Query interface
  • Named parameter binding
  • Pagination control

_at_Session public class ItemDAOImpl
public List findByDescription(String de
scription, int page) return em.createQuery(
from Item i where i.description like d)
.setParameter(d, description)
.setMaxResults(50) .setFirstResul
t(page50) .listResults()
51
EJB QL 3.0
  • EJBQL 3.0 is very similar to HQL (Hibernate Query
    Language)
  • Aggregation, projection
  • select max(b.amount) from Bid b where b.item
    id
  • select new Name(c.first, c.last) from Customer c
  • Fetching
  • from Item i left join fetch i.bids
  • Subselects
  • from Item i join i.bids bid where bid.amount
    (select max(b.amount) from i.bids b)
  • Group By, Having, Joins

52
Inheritance
  • Persistence mapping supports inheritance
  • Single table per hierarchy SINGLE_TABLE
  • Join table per subclass JOINED
  • Distinct table per subclass UNION
  • Queries on class hierarchy are polymorphic

53
Inheritance SINGLE_TABLE
_at_Entity _at_Table(name"Animal") _at_Inheritance(strat
egyInheritanceType.SINGLE_TABLE)
_at_DiscriminatorColumn(name"TYPE")
public class Animal _at_Id private int id
_at_Column(name"AVG_WEIGHT") private int average
Weight ... _at_Entity _at_Inheritance(strategy
InheritanceType.SINGLE_TABLE) public class Dog ex
tends Animal _at_Column(name"BREED") private
String breed ...
54
Inheritance SINGLE_TABLE
create table Animal ( ID Number, TYPE varchar(
255),
AVG_WEIGHT Number, BREED varchar(255) )
55
Inheritance JOINED
_at_Entity _at_Inheritance(strategyInheritanceType.JOI
NED) _at_DiscriminatorColumn(name"TYPE") _at_Table(na
me"Animal") public class Animal _at_Id private
int id _at_Column(name"AVG_WEIGHT") privat
e int averageWeight ... _at_Entity _at_Inherita
nceJoinColumn(name"DOGGY_ID")
_at_Table(name"Doggy") public class Dog extends Ani
mal _at_Column(name"BREED") private String br
eed ...
56
Inheritance JOINED
create table Animal ( ID Number, TYPE varchar(2
55), AVG_WEIGHT Number ) create table Doggy

( DOGGY_ID Number, BREED varchar(255) )
57
Inheritance UNION
create table Kitty ( ID Number, TYPE varchar(25
5), AVG_WEIGHT Number BREED varchar(255), LIVES
Number ) create table Doggy ( DOGGY_ID Nu
mber, TYPE varchar(255), AVG_WEIGHT Number BRE
ED varchar(255) )
58
Upcoming Features
  • Currently in committee

59
Interceptors
  • Interceptors intercept calls
  • Interceptors sit between caller and a session
    bean
  • Analogous to servlet filters
  • Can only be used with session and message driven
    beans
  • Precursor to full aspect-oriented programming

interceptor
public class CartBean public void buy()

cart.buy(product)
60
Why Interceptors
  • Tracing
  • Pluggable auditing
  • Custom security
  • Generic exception handling

61
Interceptors
  • Interceptor is a plain Java class
  • A method can be designated as the interceptor
    method
  • _at_AroundInvoke
  • That method must return Object and throw
    Throwable
  • That method must also accept an
    InvocationContext
  • InvocationContext hold information about the
    request
  • Request can be aborted with an exception
  • Exceptions can be caught from the bean class and
    suppressed
  • Return objects can be changed
  • Arguments can be modified

62
Interceptors
public class RuleBasedSecurityInterceptor
boolean checkRule() _at_AroundInvoke
public Object customSecurity(InvocationContex
t ctx) throws Exception if (checkRule(
) false) throw new SecurityExcep
tion(Custom check failed) r
eturn ctx.proceed()
63
Exception handling
public class OracleExceptionHandlerInterceptor
public final static int ORACLE_DEADLOCK
_at_AroundInvoke public Object
customSecurity(InvocationContext ctx) throws
Exception try return ct
x.proceed() catch (SQLException ex)
switch (ex.getErrorCode())
case ORACLE_DEADLOCK
throw new DeadlockException(ex
)

64
Callback Listeners
  • Similar to interceptors
  • Intercept EJB callback methods in a separate
    class
  • Can be attached to entities, sessions, or MDBs

Callback Listener
_at_Entity public class CartBean _at_PostCreate
public void initialize()

POST CREATE EVENT
65
Callback Listeners
public class CallbackTracer _at_PostCreate
public void tracePosCreate()
log.trace(postcreate)
_at_PreUpdate public void tracePreUpdat
e log.trace(preupdate)

66
JBoss Inc.
  • EJB 3.0 Preview Available NOW!
  • Download at www.jboss.org
  • Tutorial with code examples
  • Preview 3 due out end of month
  • Mostly functional
  • 10 Discount for JUG members on all training
  • EJB 3.0 training coming soon
Write a Comment
User Comments (0)