2. Goal
Learn how EJB 3.0 technology simplifies
Java EE application development
3. Content
Overview and Background
EJB 3.0 - Whatâs New ?
EJB 3.0 API
EJB 3.0 Persistence
Compatibility and Migration
Summary
Resources
Agenda
4. What is EJB?
A server side component architecture for the development
and deployment of distributed, enterprise applications in
Java.
Typically contain the business logic of an enterprise
application
EJB applications are scalable, transactional, multi-user and
secure.
EJB components are managed by the EJB container that is
part of a Java EE server
6. Advantages of EJB
Write Once, Deploy Anywhere
Frees the application developer from having to deal
with the system level aspects of an application.
Behavior can be configured at deployment without
modifying the source code
Rapid and simplified development of distributed,
transactional, secure and portable Java EE applications
7. Types of EJBs
Session Bean
Stateful Session Bean
Stateless Session Bean
Entity Bean
⢠Based on persistence types,
Bean managed
Container managed
Message Driven Bean
8. An EJB 2.1 Example
8
// Bean class
public class HelloBean implements SessionBean {
private SessionContext sessionContext;
public void ejbCreate() { }
public void ejbRemove() { }
public void ejbActivate() { }
public void ejbPassivate() { }
public void setSessionContext(SessionContext sessionContext) {
this.sessionContext = sessionContext;
}
public String sayHello() {
return "Hello World!!!!!";
}
}
// Home Interface
public interface HelloHome extends EJBHome {
public Hello create() throws RemoteException, CreateException;
}
// Remote Interface
public interface Hello extends EJBObject {
public String sayHello() throws RemoteException;
}
9. An EJB 2.1 Example (Contd.)
9
// Entry in ejb-jar.xml (deployment descriptor)
<session>
<ejb-name>Hello</ejb-name>
<home>com.jlive.demo.hello.HelloHome</home>
<remote>com.jlive.demo.hello.Hello</remote>
<ejb-class>com.jlive.demo.hello.HelloBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Bean</transaction-type>
</session>
//Client code
public class HelloClient {
public static void main(String [] args) throws Exception {
Context jndiContext = new InitialContext();
Object ref = jndiContext.lookup("Hello");
HelloHome helloHome = (HelloHome)
PortableRemoteObject.narrow(ref,
HelloHome.class);
Hello hello = helloHome.create();
System.out.println(hello.sayHello());
}
}
10. What was wrong with EJB 2.1?
EJB 2.1 technology
Very powerful, but complex to use
Too many classes, interfaces
Java Naming and Directory Interfaceâ˘(JNDI) API lookups
javax.ejb interfaces
Awkward programming model
Deployment descriptors
Entity bean anti-patterns
Difficult to test entities outside the container
11. EJB 3.0 - Whatâs New ?
Simplification of the EJB APIs
Utilizes advantages of Java metadata annotations
More work is done by container, less by developer
Dependency injection
New Persistence API Specification
12. EJB 3.0 Bean Simplification
Elimination of EJB component interfaces
Business interfaces are plain Java interfaces
Elimination of Home interfaces
Only need business interface, not home
Elimination of requirements for
javax.ejb.EnterpriseBean interfaces
Annotations for (optional) callbacks
Elimination of need for use of JNDI API
Use dependency injection, simple lookup method
13. Example â EJB 3.0
13
// Bean class
@Stateless
public class NewHelloBean implements NewHello{
public String sayHello() {
return "Hello New World!!!!!";
}
}
// Business Interface
@Remote
public interface NewHello {
public String sayHello();
}
// Client code
public class NewHelloClient
{
public static void main(String [] args) throws Exception {
Context jndiContext = new InitialContext();
Object ref = jndiContext.lookup("NewHello");
NewHello hello = (NewHello)ref;
System.out.println(hello.sayHello());
}
}
14. MDB in EJB 3.0
14
@MessageDriven(activateConfig = {
@ActivationConfigProperty(propertyName="destinationTy
pe", propertyValue="javax.jms.Queue"),
@ActivationConfigProperty(propertyName="destination",
propertyValue="queue/mdb") })
public class CalculatorBean implements MessageListener {
public void onMessage (Message msg) {
try {
TextMessage tmsg = (TextMessage) msg;
} catch (Exception e) { e.printStackTrace (); } }
// ... ... }
Message driven beans are components designed to handle
message based requests
The MDB must implement the Message Listener interface.
The on Message method is invoked when a message is
received by the container
15. Resource Injection
Resource injection is an inversion of dependency
Resources can be injected on bean creation
References of
DataSources, UserTransaction, Environment entries,
EntityManager, Other EJB beans
Annotations
@EJB
@Resource
Injection can be specified using deployment descriptor
19. EJB 3.0 Transactions
19
CMT by default, BMT by annotation
Specified at class level or method level
Default is CMT + REQUIRED
20. ⢠// Uses container-managed transaction, REQUIRED attribute
⢠@Stateless public PayrollBean implements Payroll {
⢠@TransactionAttribute(MANDATORY)
⢠public void setBenefitsDeduction(int empId, double
deduction) {...}
⢠public double getBenefitsDeduction(int empId) {...}
⢠public double getSalary(int empid) {...}
⢠@TransactionAttribute(REQUIRES_NEW)
⢠public void setSalary(int empId, double salary) {...}
⢠}
21. EJB 3.0 Security
21
Security configuration preferred at deployment
Annotations - @Unchecked, @RolesAllowed
Default is unchecked
// Security view
@Stateless public PayrollBean implements Payroll {
public void setBenefitsDeduction(int empId, double deduction)
{...}
public double getBenefitsDeduction(int empId) {...}
public double getSalary(int empid) {...}
// salary setting is intended to be more restricted
@RolesAllowed(âHR_PayrollAdministratorâ)
public void setSalary(int empId, double salary) {...}
}
22. EJB 3.0 Callback - Event Notification
22
Container calls bean upon lifecycle events
@PostConstruct, @PreDestroy, @PrePassivate, @PostActivate,âŚ
Bean specifies events it needs to know about
Callback methods can be specified on lifecycle listener
24. EJB 3.0 Interceptors
Interception of invocations of business methods and/or
message listener methods
Invocation model: âaroundâ methods
Wrapped around business method invocations
Interceptor has control over invocation of ânext methodâ
Can manipulate arguments and results
Context data can be carried across invocation chain
Execute in specified order
Can use deployment descriptor to override order or add
interceptors
Annotations
ď§ @Interceptors, @AroundInvoke
25. EJB 3.0 Interceptors - Example
25
@Interceptors({
com.demo.AuditInterceptor.class,
com.demo.LoggerInterceptor.class
})
@Stateless
public class AccountManagementBean implements
AccountManagement {
public void createAccount(int accountId, Details
details) {...}
public void deleteAccount(int accountId) {...}
}
public class AuditInterceptor {
@AroundInvoke
public Object
auditOperation(InvocationContext inv) {
try {
Object result = inv.proceed();
// Add auditing code here
return result;
} catch (Exception ex) {
âŚ
}
}
26. Persistence API
26
Can be used outside Java EE platform-based containers
also
Evolution into âcommonâ Java persistence API
Support for pluggable third-party persistence providers
27. Persistence Model
27
Entities are simple Java classes
Concrete java classes
No required interfaces
Usable as âdetachedâ objects in other tiers
No more need for DTOs
EntityManager is used to manage entities
Creates, removes and finds entities
Usable across multiple transactions, spanning multiple
user requests
Extended persistence context
28. EJB 3.0 Entity - Example
28
Order.java
@Entity
@Table(name="ORDER_TABLE")
public class Order {
@Id
@GeneratedValue
protected long orderId;
@OneToOne
protected Item item;
...
}
Item.java
@Entity
public class Item {
protected long SKU;
@Id
@GeneratedValue
public long getSKU() { return SKU; }
}
29. Entity Manager
29
Provides entity operations
Methods for lifecycle operations
Persist, remove, merge, flush, refresh, etc.
Convenience query methods (find)
EntityManager is factory for Query objects
Static (named) and dynamic queries, EJB QL and SQL
queries
Manages persistence context
Both transaction-scoped and extended persistence
contexts
Similar in functionality to Hibernate Session, JDO
PersistenceManager, etc.
30. EJB 3.0 Entity Manager- Example
30
// Creating the entity
public void createNewOrder(Order order){
EntityManager em = getEntityManager();
try{
em.getTransaction().begin();
em.persist(order);
em.getTransaction().commit();
}
finally{ em.close(); } }
// Finding and updating the entity
public void alterOrderQuantity(long orderId, int
newQuantity){
EntityManager em = getEntityManager();
try{
em.getTransaction().begin();
Order order = em.find(Order.class,
orderId);
order.setQuantity(newQuantity);
em.getTransaction().commit();
}finally{ em.close(); } }
31. 31
Named queries are predefined static queries that are precompiled.
They can take parameters, but the query remains the same.
@NamedQuery(
name="MyEntity.getItemsPerProductCategory",
query="SELECT i FROM Item i WHERE i.product.categoryID
LIKE :cID"
)
@Entity
public class MyEntity { ...
}
// Using named queries
public class MyDataFacade ... {
private EntityManager em;
...
public List<Items> getItems(String catID) {
Query query =
em.createNamedQuery("MyEntity.getItemsPerProduct
Category");
query.setParameter("cID",catID);
List<Item> items = query.getResultList();
return items;
}
32. EJB â Compatibility and
Migration
32
Existing applications continue to work
Provides integration with existing applications and
components
Allows components to be updated or replaced (using
EJB 3.0 APIs) without affecting existing clients
Facilitates EJB 3.0 technology adoption with
incremental migration
33. Migrating EJB 2.1 to EJB 3.0
33
0
2
4
6
8
10
12
14
16
18
# of Java Files # of XML Files
EJB 2.1
EJB 3.0
No. of files EJB
2.1
EJB
3.0
Java Files 17 7
XML Files 9 2
ďŽ Migration of the RosterApp, available as a sample
application in public domain
ďŽ No. of files comparison %
41%
22%
34. Migrating EJB 2.1 to EJB 3.0
34
Lines of Code
in
EJB2.1 EJB3.0 %
Java File 987(17) 716(7) 73%
XML File 792(9) 26(2) 3%
ďŽ Migration of the RosterApp, available as a sample
application in public domain
ďŽ LOC comparison
0
100
200
300
400
500
600
700
800
900
1000
# of lines (Java) # of lines (XML)
EJB 2.1
EJB 3.0
35. EJB 3.0 Summary
35
ďŽ EJB technology simplified for developers
Fewer classes and interfaces
Injection model for container services and resources
Removal of boilerplate code
Elimination of need for deployment descriptors
Independent Persistence specification
Entities are POJOs enabling detached entities
Improved query capabilities
O/R mapping specification
ďŽ EJB 3.0 applications interoperate with existing applications
36. Resources
⢠JSR 220: Enterprise JavaBeansâ˘,Version 3.0
EJB 3.0 Simplified API
EJB Core Contracts and Requirements
Java Persistence API
⢠Enterprise JavaBeans Technology
http://java.sun.com/products/ejb/
⢠EJB
http://dev2dev.bea.com/ejb/
⢠The Simplicity of EJB 3.0/
http://java.sys-con.com/read/117755_1.htm
36