EJB 3'0

1 / 89
About This Presentation
Title:

EJB 3'0

Description:

... eager loading of relationships. Cascades: delete, create, and ... No CMR: You must manage your relationships. JBoss Group, 2003. 38. Professional Open Source ... – PowerPoint PPT presentation

Number of Views:63
Avg rating:3.0/5.0
Slides: 90
Provided by: me6130

less

Transcript and Presenter's Notes

Title: EJB 3'0


1
EJB 3.0
  • Bill Burke
  • Chief Architect
  • JBoss Inc.

2
Overall Agenda
  • Overview
  • Session Beans
  • Interceptors
  • Entity Beans
  • JBoss Extensions

3
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

4
Session Beans
  • Compare EJB 2.1 vs. EJB 3.0

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

6
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()
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

7
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
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
8
EJB 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 .
9
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

10
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 CalculatorBean
implements Calculator public int add(int x, int
y) return x y public int subtract(int x,
int y) Return x y
11
EJB 3.0 XML Deployment Descriptor
12
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 class
ShoppingCartBean implements ShoppingCart
_at_Remove public void checkout()
13
MDBs
  • Just implements MessageListener
  • XML turns to annotations

_at_MessageDriven( activationConfigActivati
onConfigProperty(namedestination,
valuequeue/email)) public class EmailBean
implements MessageListener void
onMessage(Message msg)
14
Transactions and Security
_at_Stateful public class ShoppingCartBean
implements ShoppingCart
_at_Remove _at_TransactionAttribute(REQUIRED) _at_MethodPer
mission(valid_customer) public void
checkout()
15
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_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
16
EJB 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()
17
EJB 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

18
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_Remove _at_TransactionAttribute(REQUIRED) _at_Metho
dPermission(valid_customer) public void
checkout()
19
EJB 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()
20
XML 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
21
Interceptors
22
Interceptors
_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

24
Interceptors
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()
25
Interceptors
_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
26
Default 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
27
Intercepting 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

28
Intercepting Callbacks
_at_Stateless _at_Interceptor(JndiInjector.class) public
class JndiInjector _at_JndiInject(java/Trans
actionManager) TransactionManager tm
Custom injection annotation
29
Intercepting Callbacks
public class JndiInjector _at_PostConstruct
public void injector(InvocationContext ctx)
injectIntoAllFieldsWithJndiInjectAnnotation(
ctx.getTarget())
30
Entity Beans
  • POJO based persistence

31
Goals 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

32
Defining Entity Beans
  • Full Object/Relational Database Mapping

33
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_Embedded
  • Inheritance, _at_Inheritance, _at_DiscriminatorColumn
  • Identifier Version properties, _at_Id, _at_Version

34
Entity 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
35
Entity 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 )
36
Entity 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
37
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 your relationships.

38
Entity 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
39
Entity 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 )
40
No CMR
_at_OneToMany(cascadeALL)
_at_JoinColumn(nameITEM_ID) public SetltBidgt
getBids() return bids
public void addBid(Bid bid)
getBids().add(bid) bid.setItem(this)

41
Multi-Table
  • Multi-Table Mappings,
  • Entity can be stored in one or more tables
  • _at_SecondaryTables, _at_SecondaryTable

42
Multi-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
43
Multi-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) )
44
Embedded Objects
  • Embedded Objects
  • Aggregated objects whose properties can be mapped
  • _at_Embedded, _at_Embeddable

45
Embedded 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
46
Embedded
_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

47
Composite Keys/Primary Key Classes
  • EJB 2.1 style primary keys
  • Same idea as _at_Embedded
  • _at_EmbeddedId, _at_Embeddable, _at_IdClass

48
Composite 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
49
Composite 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
50
Inheritance
  • 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

51
Inheritance 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 ...
52
Inheritance SINGLE_TABLE
create table Animal ( ID Number, TYPE
varchar(255), AVG_WEIGHT Number, BREED
varchar(255) )
53
Inheritance 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 ...
54
Inheritance JOINED
create table Animal ( ID Number, TYPE
varchar(255), AVG_WEIGHT Number ) create table
Doggy ( DOGGY_ID Number, BREED varchar(255) )
55
Inheritance 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) )
56
Interacting With Entity Bean
  • Plain Java Objects

57
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

58
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(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)
59
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

60
EntityManager
_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
61
EntityManager
_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

62
EntityManager
_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

63
EntityManager
_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

64
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_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()
65
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

66
JBoss Extensions to EJB 3
  • From EJBs to Enterprise POJOs

67
The Service Bean
68
Service bean
  • Singleton services
  • Multi-threaded and stateful
  • Lifecycle and dependency management
  • Next iteration of the JBoss MBean

69
Service 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

70
Service 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)
71
Service interfaces
  • _at_Management
  • JMX interface, JMX aspect

_at_Management public interface CalculatorManagement
int getPrecision() void setPrecision()
72
Service 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)
73
Message Driven POJOs
  • Typed MDBs

74
Message Driven POJOs
  • MDBs with a typed interface
  • MDBs that publish a well known interface
  • Simplify JMS
  • Invoke methods, dont build messages
  • Cleaner, clearer code

75
Message 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)
78
Using 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)
79
Configuring 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)
80
Asynchronous EJBs
  • Lightweight asynchronous communication

81
Asynchronous 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.

82
Asynchronous 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)
83
Asynchronous 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
84
Asynchronous 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()
85
Summary
  • 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

86
JBoss 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

88
Book
  • OReilly EJB 3.0 5th Edition

89
JBoss World Las Vegas
  • JBoss World Las Vegas
  • June 12-15
  • Rio Hotel Casino
  •  
  • www.jbossworld.com
  • 10 discount code bw1jg
  •  
  •  
  •  
Write a Comment
User Comments (0)