Title: EJB 3'0
1EJB 3.0
- Bill Burke
- Chief Architect
- JBoss Inc.
2Overall Agenda
- Overview
- Session Beans
- Interceptors
- Entity Beans
- JBoss Extensions
3Goals 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
4Session Beans
- Compare EJB 2.1 vs. EJB 3.0
5EJB 2.1 Requirements
- Home interface
- Remote/Local interface
- Bean class must implement javax.ejb.SessionBean
- XML Deployment descriptor
6EJB 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()
throws CreateException public interface
Calculator extends EJBObject public int add(int
x, int y) throws RemoteException public int
subtract(int x, int y) throws RemoteException
7EJB 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
ctx public void setSessionContext(SessionContext
ctx) this.ctx ctx public void ejbCreate()
public void ejbRemove() public void
ejbActivate() public void ejbPassivate()
public int add(int x, int y) return x
y public int subtract(int x, int y) return
x y
8EJB 2.1 XML Deployment Descriptor
ltsessiongt ltejb-namegtCalculatorBeanlt/ejb-namegt lthom
egtorg.acme.CalculatorHomelt/homegt ltbeangtorg.acme.Ca
lculatorBeanlt/beangt ltremotegtorg.acme.CalculatorRem
otelt/remotegt ltsession-typegtStatelesslt/session-type
gt lttransaction-typegtContainerlt/transaction-typegt lt
/sessiongt .
9EJB 3.0 Goals
- Remove unnecessary interfaces
- Remove unnecessary callbacks
- Make deployment descriptors optional
- Make beans pojo-like
- Use default values where they make sense
10Required 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 CalculatorBean
implements Calculator public int add(int x, int
y) return x y public int subtract(int x,
int y) Return x y
11EJB 3.0 XML Deployment Descriptor
12Stateful 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 class
ShoppingCartBean implements ShoppingCart
_at_Remove public void checkout()
13MDBs
- Just implements MessageListener
- XML turns to annotations
_at_MessageDriven( activationConfigActivati
onConfigProperty(namedestination,
valuequeue/email)) public class EmailBean
implements MessageListener void
onMessage(Message msg)
14Transactions and Security
_at_Stateful public class ShoppingCartBean
implements ShoppingCart
_at_Remove _at_TransactionAttribute(REQUIRED) _at_MethodPer
mission(valid_customer) public void
checkout()
15EJB 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_Resource private
SessionContext ctx _at_EJB private
CreditCardProcessor processor private
DataSource jdbc _at_Resource(mappedNamejava/Defa
ultDS) public void setDataSource(DataSource db)
this.jdbc db
16EJB 3.0 Callbacks on demand
- Callback methods still available
- Annotate on an as-needed basis
_at_Stateless public class FacadeBean implements
Facade _at_Timeout void licenseExpired(Timer t)
_at_PostActivate public void initialize()
17EJB 3.0 Deployment Descriptor
- Believe it or not, people like XML deployment
descriptors - Externalize configuration
- Externalize system architecture
- Replace annotations with XML and you get pure
POJOs
18EJB 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_Remove _at_TransactionAttribute(REQUIRED) _at_Metho
dPermission(valid_customer) public void
checkout()
19EJB 3.0 Deployment Descriptors
public interface ShoppingCart public void
addItem(int prodId, int quantity) public void
checkout() public class ShoppingCartBean
implements ShoppingCart public void
checkout()
20XML Descriptors
- Partial deployment descriptors supported
- Start off with annotations, configure as needed
ltejb-jargt ltenterprise-beansgt ltsessiongt
ltejb-namegtShoppingCartBeanlt/ejb-namegt
ltejb-local-refgt
ltejb-ref-namegtprocessorlt/ejb-ref-namegt
ltlocalgtcom.titan.CreditCardProcessorlt/localgt
lt/ejb-local-refgt lt/sessiongt
lt/enterprise-beansgt lt/ejb-jargt
21Interceptors
22Interceptors
_at_Stateless public class CartBean public void
buy()
interceptor
cart.buy(product)
- 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
23 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
24Interceptors
public class RuleBasedSecurityInterceptor
boolean checkRule() _at_AroundInvoke
public Object customSecurity(InvocationContext
ctx) throws Exception if (checkRule()
false) throw new
SecurityException(Custom check failed)
return ctx.proceed()
25Interceptors
_at_Stateful _at_Interceptors(RuleBasedSecurityIntercept
or.class) public class ShoppingCartBean
implements ShoppingCart void buy()
_at_Interceptors(RuleBasedSecurityInterceptor.class)
public void checkout()
All methods in class
Per method
26Default Interceptors
ltejb-jargt ltassembly-descriptorgt
ltinterceptor-bindinggt ltejb-namegtlt/ejb-na
megt ltinterceptor-classgtorg.jboss.RuleBase
dSecuritylt/interceptor-classgt
lt/interceptor-bindinggt lt/assembly-descriptorgt lt
/ejb-jargt
Every bean in deployment
27Intercepting callbacks
Interceptor
_at_Stateful public class CartBean
_at_PostConstruct public void initialize()
POST CONSTRUCT EVENT
- Callback events can be intercepted
- Work same as _at_AroundInvokes
28Intercepting Callbacks
_at_Stateless _at_Interceptor(JndiInjector.class) public
class JndiInjector _at_JndiInject(java/Trans
actionManager) TransactionManager tm
Custom injection annotation
29Intercepting Callbacks
public class JndiInjector _at_PostConstruct
public void injector(InvocationContext ctx)
injectIntoAllFieldsWithJndiInjectAnnotation(
ctx.getTarget())
30Entity Beans
31Goals of Entity Beans
- Same goals as session beans
- Fewer interfaces, optional XML DDs, etc.
- No required interfaces or subclassing
- Plain Java based
- Allocated with new()
- Provide full Object/Relational mapping
- Supports Inheritance
- Expanded EJBQL
- Fully featured
- Parallel SQL
- Polymorphic Queries
32Defining Entity Beans
- Full Object/Relational Database Mapping
33EJB 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_Embedded
- Inheritance, _at_Inheritance, _at_DiscriminatorColumn
- Identifier Version properties, _at_Id, _at_Version
34Entity Annotations
_at_Entity _at_Table(nameAUCTION_ITEM) public class
Item private long id private String
description private String productName
private SetltBidgt bids new HashSet()
private User seller _at_Id _at_GeneratedValue
_at_Column(nameITEM_ID) public long getId()
return id public void
setId(long id) this.id id
relational table declaration
auto-key generation
35Entity Annotations
_at_Entity _at_Table(nameAUCTION_ITEM) public class
Item private long id private String
description private String productName
private SetltBidgt bids new HashSet()
private User seller _at_Id _at_GeneratedValue
_at_Column(nameITEM_ID) public long getId()
return id public void
setId(long id) this.id id
create table AUCTION_ITEM ( ITEM_ID Number, DESC
varchar(255), ProductName varchar(255), USER_ID
Number )
36Entity Annotations
_at_Column(nameDESC, length500) public
String getDescription() return
description public void
setDescription(String desc)
this.description desc public
String getProductName() return
productName protected void
setProductName(String name)
this.productName name
column mapping
intuitive defaults
37Relationships
- 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 your relationships.
38Entity Relationships
_at_OneToOne(fetchLAZY) _at_JoinColumn(nameOWNE
R_ID) public Owner getOwner()
return owner public void
setOwner(Owner owner) this.owner
owner _at_OneToMany(cascadeALL)
_at_JoinColumn(nameITEM_ID) public SetltBidgt
getBids() return bids
public void setBids(SetltBidgt bids)
this.bids bids
lazy/eager loading
various cascade types
39Entity Relationships
_at_OneToOne(fetchLAZY) _at_JoinColumn(nameOWNE
R_ID) public Owner getOwner()
return owner public void
setOwner(Owner user) this.owner
owner _at_OneToMany(cascadeALL)
_at_JoinColumn(nameITEM_ID) public SetltBidgt
getBids() return bids
public void setBids(SetltBidgt bids)
this.bids bids
create table AUCTION_ITEM ( ITEM_ID Number, DESC
varchar(255), ProductName varchar(255), OWNER_ID
Number ) create table BID ( ITEM_ID
Number )
40No CMR
_at_OneToMany(cascadeALL)
_at_JoinColumn(nameITEM_ID) public SetltBidgt
getBids() return bids
public void addBid(Bid bid)
getBids().add(bid) bid.setItem(this)
41Multi-Table
- Multi-Table Mappings,
- Entity can be stored in one or more tables
- _at_SecondaryTables, _at_SecondaryTable
42Multi-table Mappings
_at_Entity _at_SecondaryTable(nameADDRESS,
pkJoinColumns
_at_PrimaryKeyJoinColumn(nameADDR_ID)) public
class Owner private long id private
String name private String street
private String city private String state
_at_Id _at_GeneratedValue public long getId()
return id public void
setId(long id) this.id id
create table OWNER ( ID Number, NAME
varchar(255), ) create table ADDRESS ( ADDR_ID
Number, STREET varchar(255), CITY
varchar(255), STATE varchar(255) )z
43Multi-Table Mappings
_at_Column(nameSTREET, tableADDRESS)
public String getStreet() return
street public void setStreet(String
street) this.street street
_at_Column(nameCITY, tableADDRESS)
public String getCity() return city
protected void setCity(String city)
this.city city
create table OWNER ( ID Number, NAME
varchar(255), ) create table ADDRESS ( ADDR_ID
Number, STREET varchar(255), CITY
varchar(255), STATE varchar(255) )
44Embedded Objects
- Embedded Objects
- Aggregated objects whose properties can be mapped
- _at_Embedded, _at_Embeddable
45Embedded Objects
_at_Entity public class Owner private long
id private String name private Address
address _at_Id _at_GeneratedValue public long
getId() return id public
void setId(long id) this.id id
public String getName()
_at_Embeddable public class Address private
String street private String city private
String state _at_Column(STREET) public
String getStreet() return street
public void setStreet(String street)
this.street street public String
getCity() return city
46Embedded
_at_Embedded( _at_AttributeOverride(names
treet, _at_Column(nameSTREET)),
_at_AttributeOverride(namecity,
_at_Column(nameCITY)), _at_AttributeOverride(
namestate, _at_Column(nameSTATE))) public
Address getAddress() return address
public void setAddress(Address address)
this.address address
47Composite Keys/Primary Key Classes
- EJB 2.1 style primary keys
- Same idea as _at_Embedded
- _at_EmbeddedId, _at_Embeddable, _at_IdClass
48Composite Keys
_at_Entity public class Owner private OwnerPK
pk private Address address _at_EmbeddedId
public OwnerPK getId() return id
public void setId(OwnerPK id)
this.id id
_at_Embeddable public class OwnerPK private
String name private long ssn
_at_Column(NAME) public String getName()
return street public long getSSN()
return sn
49Composite Keys
_at_Entity _at_IdClass(OwnerPK.class) public class
Owner _at_Id String name _at_Id long ssn
_at_Embedded Address address
_at_Embeddable public class OwnerPK private
String name private long ssn
_at_Column(NAME) public String getName()
return street public long getSSN()
return sn
50Inheritance
- Persistence mapping supports inheritance
- Single table per hierarchy SINGLE_TABLE
- Join table per subclass JOINED
- Distinct table per subclass TABLE_PER_CLASS
- Queries on class hierarchy are polymorphic
51Inheritance SINGLE_TABLE
_at_Entity _at_Table(name"Animal") _at_Inheritance(strateg
yInheritanceType.SINGLE_TABLE) _at_DiscriminatorColu
mn(name"TYPE") public class Animal _at_Id
private int id _at_Column(name"AVG_WEIGHT")
private int averageWeight ... _at_Entity _at_Inherit
ance(strategyInheritanceType.SINGLE_TABLE) public
class Dog extends Animal _at_Column(name"BREED")
private String breed ...
52Inheritance SINGLE_TABLE
create table Animal ( ID Number, TYPE
varchar(255), AVG_WEIGHT Number, BREED
varchar(255) )
53Inheritance JOINED
_at_Entity _at_Inheritance(strategyInheritanceType.JOIN
ED) public class Animal _at_Id private int id
_at_Column(name"AVG_WEIGHT") private int
averageWeight ... _at_Entity _at_InheritanceJoinColu
mn(name"DOGGY_ID") public class Dog extends
Animal _at_Column(name"BREED") private String
breed ...
54Inheritance JOINED
create table Animal ( ID Number, TYPE
varchar(255), AVG_WEIGHT Number ) create table
Doggy ( DOGGY_ID Number, BREED varchar(255) )
55Inheritance TABLE_PER_CLASS
create table Kitty ( ID Number, TYPE
varchar(255), AVG_WEIGHT Number BREED
varchar(255), LIVES Number ) create table Doggy
( DOGGY_ID Number, TYPE varchar(255), AVG_WEIGHT
Number BREED varchar(255) )
56Interacting With Entity Bean
57Entity 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
58Create 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(Orei
llys EJB 3.0 5th Edition) item.setProductName(
EJB 3.0 Book) Owner bill new
Owner() bill.setName(Bill) item.setOwner(bill)
Bid bid new Bid() HashSetltBidgt bids new
HashSet() bids.add(bid) item.setBids(bids)
59Entity 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
60EntityManager
_at_Stateless public class ItemDAOImpl implements
ItemDAORemote _at_PersistenceContext(unitName
Auction) private EntityManager em
public long create(Item item)
em.persist(item) return item.getId()
public Item findById(long id)
return em.find(Item.class, id) public
void merge(Item item) em.merge(item)
Inject the EntityManager service
61EntityManager
_at_Stateless public class ItemDAOImpl implements
ItemDAORemote _at_PersistenceContext(unitName
Auction) private EntityManager em
public long create(Item item)
em.persist(item) return item.getId()
public Item findById(long id)
return em.find(Item.class, id) public
void merge(Item item) em.merge(item)
- Item allocated remotely
- If cascade PERSIST, entire object graph inserted
into storage
62EntityManager
_at_Stateless public class ItemDAOImpl implements
ItemDAORemote _at_PersistenceContext(unitName
Auction) private EntityManager em
public long create(Item item)
em.persist(item) return item.getId()
public Item findById(long id)
return em.find(Item.class, id) public
void merge(Item item) em.merge(item)
- Item found with primary key
- Detached from persistent storage at tx
completion - Can be serialized like any other object
63EntityManager
_at_Stateless public class ItemDAOImpl implements
ItemDAORemote _at_PersistenceContext(unitName
Auction) private EntityManager em
public long create(Item item)
em.persist(item) return item.getId()
public Item findById(long id)
return em.find(Item.class, id) public
void merge(Item item) em.merge(item)
- Item can be updated remotely and changes merged
back to persistent storage - merge() returns a managed copy of Item
64Query 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_Stateless public class ItemDAOImpl
public List findByDescription(String description,
int page) return em.createQuery(from Item
i where i.description like d)
.setParameter(d, description)
.setMaxResults(50) .setFirstResult(page50
) .getResultList()
65EJB 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
66JBoss Extensions to EJB 3
- From EJBs to Enterprise POJOs
67The Service Bean
68Service bean
- Singleton services
- Multi-threaded and stateful
- Lifecycle and dependency management
- Next iteration of the JBoss MBean
69Service bean
- Full EJB 3 library of annotations available
- _at_TransactionAttribute, _at_MethodPermissions,
_at_Inject - _at_Remote and _at_Local interface publishing
- New _at_Management interface
- JMX is now an aspect
70Service interfaces
- _at_Remote, _at_Local
- Just like EJB
_at_Remote public interface CalculatorRemote
BigDecimal add(float x, float y) BigDecimal
divide(float x, float y)
71Service interfaces
- _at_Management
- JMX interface, JMX aspect
_at_Management public interface CalculatorManagement
int getPrecision() void setPrecision()
72Service bean class
- _at_Service deploys a singleton
- Multi-threaded and stateful
_at_Service public class CalculatorService
implements CalculatorRemote, CalculatorManagement
private int precision public int
getPrecision() return precision void
setPrecision(int p) precision p
BigDecimal divide(float x, float y)
73Message Driven POJOs
74Message Driven POJOs
- MDBs with a typed interface
- MDBs that publish a well known interface
- Simplify JMS
- Invoke methods, dont build messages
- Cleaner, clearer code
75Message Driven POJOs
- Define a _at_Consumer bean class
- _at_Consumer implements 1-N _at_Producer interfaces
- _at_Producer a means to send JMS messages
- _at_Consumer a means to receive JMS messages
76_at_Producer
_at_Producer public interface EmailRemote public
void send(String msg) public void send(String
to, String from, String msg, Map props)
77_at_Consumer
_at_Consumer(activation
ActivationConfigProperty(namedestinationType,
valuejavax.jms.queue),
ActivationConfigProperty(namedestination,
valuequeue/foo) ) public class
EmailerBean implements EmailRemote
public void send(String msg) public
void send(String to, String from, String msg, Map
props)
78Using a Producer
- Producers implicitly extend ProducerObject
interface
EmailRemote emailer (EmailRemote)ctx.lookup
(EmailRemote.class.getName())
ProducerConfig.connect(emailer)
emailer.send(spam) emailer.send(bill_at_jboss.
org, tss_at_tss.com, spam, new HashMap())
ProducerConfig.close(emailer)
79Configuring Message Properties
_at_Producer(transactedtrue) _at_MessageProperties(deli
veryNON_PERSISTENT) public interface EmailRemote
_at_MessageProperties(de
liveryPERSISTENT, timeToLive1000,
priority1) public void send(String msg) public
void send(String to, String from, String msg, Map
map)
80Asynchronous EJBs
- Lightweight asynchronous communication
81Asynchronous EJBs
- Goals
- Provide a lightweight asynchronous API for all
EJB types - VM local and Remote capabilities
- Zero changes to existing interfaces/code
- Support obtaining method results asychronously
- Not just oneway.
82Asynchronous EJBs
- Available for Stateless, Stateful, and Service
- Each _at_Remote and _at_Local interface implements
EJBProxy
public class Asynch public static ltTgt T
getAsynchronousProxy(Object obj)
CalculatorRemote calc
(CalculatorRemote)ctx.lookup(calculator) //
turn a synchronous EJB proxy into an asynchronous
proxy CalculatorRemote calcAsynch
Asynch.getAsynchronousProxy(calc)
83Asynchronous EJBs
- Asynchronous Proxy same exact interface
- Invoking methods on proxy happen in background
CalculatorRemote calc (CalculatorRemote)ctx.look
up(calculator) CalculatorRemote calcAsynch
Asynch.getAsynchronousProxy(calc) calcAsynch.add
(1, 1) // invoked in background, in
another thread calcAsynch.divide(10, 2) //
invoked in background
84Asynchronous EJBs
- Obtain response asynchronously
- Future interfaces
calcAsynch.add(1, 1)
// invoked in background, in another
thread Future result1 Asynch.getFutureResult(cal
cAsynch) calcAsynch.divide(10, 2)
// invoked in background Future result2
Asynch.getFutureResult(calcAsynch) int val1
result1.get() //
block until first method call returns if
(result2.isDone())
// poll to see if done int val2
result2.get()
85Summary
- Simpiler programming model
- Less artifacts, POJOs
- Annotation alternative to XML
- Rich persistence model
- EJB QL fully functional!
- Full O/R mapping
- 1. Code
- 2. Compile
- 3. Jar
- 4. Run
86JBoss Inc.
- EJB 3.0 Available NOW!
- Download at www.jboss.org
- Tutorial with code examples
- Mostly functional
87- Support Molly and Abby Burke College Fund
88Book
- OReilly EJB 3.0 5th Edition
89JBoss World Las Vegas
- JBoss World Las Vegas
- June 12-15
- Rio Hotel Casino
- Â
- www.jbossworld.com
- 10 discount code bw1jg
- Â
- Â
- Â