Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Core Systems Transformation Solutions
Enterprise Java Beans Overview. Part 1
October 15, 2015
Confidential 1
Agenda
1. Overview
2. Session Beans
3. Accessing Session Beans
4. Messaging and MDB
5. References and Injec...
Confidential 2
Overview
Confidential 3
What is EJB ?
Enterprise Java Beans
• is platform for building portable, reusable, and scalable
business ap...
Confidential 4
Java EE Components
Confidential 5
EJB container functionality
5
Resources
Client
ClientSupport
Lifecycle Management
Resource Management
EJB E...
Confidential 6
EJB Container Services
EJB Container provides valuable services for enterprise
application development:
• T...
Confidential 7
EJB Version History
 EJB 1.1 (J2EE 1.2), 1999
– Session beans (stateful & stateless), Entity Beans
– Remot...
Confidential 8
Types of Enterprise Bean Objects
• Session Beans
• Message-driven beans
• Entities
Confidential 9
Session Beans
Confidential 10
Session Beans
• Performs specific business-logic operations
• Managed by EJB Container
• Available for a c...
Confidential 11
Session Beans
Session bean object is not directly accessed
Session EJB component has the following element...
Confidential 12
Types of Session Beans
• Stateless Session Beans
• Stateful Session Beans
• Singleton Session Beans
Confidential 13
Stateless Session Bean
• Does not retain client-specific information
• A client might not get the same ses...
Confidential 14
Stateless Session Bean
EJB
EJB
EJB
EJB
EJB
Request
Instance Pool
EJB Container
Random
Selection
Confidential 15
Stateless Bean Lifecycle and Callbacks
@Stateless
public class CalculationBean {
@PostConstruct
void const...
Confidential 16
Stateless Session Bean Example
@Local
public interface CalculationLocal {
int sum(int a, int b);
}
@Statel...
Confidential 17
Stateful Session Bean
• Supports conversation state
• Is never shared, has only one client
• Client can re...
Confidential 18
Stateful Session Bean
EJB
id = 3
EJB
id = 4
EJB
id = 5
EJB
id = 1
EJB
id = 2
Request
Instance Cache
EJB Co...
Confidential 19
Stateful Bean Lifecycle and Callbacks
Confidential 20
Stateful Bean Lifecycle and Callbacks (Example)
@Stateful
public class CalculationBean implements Calculat...
Confidential 21
Singleton Session Bean
• Instantiated once per application and exists for the lifecycle
of the application...
Confidential 22
Singleton Session Bean. Concurrency Management
Singleton session beans are designed for concurrent access
...
Confidential 23
Container-Managed concurrency. Locking types
Access locking types:
javax.ejb.Lock,
javax.ejb.LockType
- @L...
Confidential 24
Container-Managed Singleton Example
@Singleton
@ConcurrencyManagement(CONTAINER)
@AccessTimeout(value=20, ...
Confidential 25
Initializing Singleton Session Beans
@Startup
@Singleton
@DependsOn({"PrimaryBean",
"SecondaryBean"})
publ...
Confidential 26
Singleton Session Beans. Errors Handling
• If a singleton session bean encounters an error when
initialize...
Confidential 27
Summary: Session Bean Types
Stateless Stateful Singleton
Has no client association Each client has its own...
Confidential 28
Accessing Enterprise
Java Beans
Confidential 29
Accessing Session Beans
 Access EJB through a no-interface view or business interface
 no-interface view...
Confidential 30
Session Bean Contracts
EJB Contracts
Local
Remote (via
Remote Interface)
As Web Service
Local Interface No...
Confidential 31
Local Interface Contract
• Run in the same JVM as the EJB
• Client: Web component or another enterprise be...
Confidential 32
Local Bean Declaration
To build an enterprise bean that allows local access:
@Local public interface Calcu...
Confidential 33
Local Contracts. No-Interface view
• No-interface view == local view
• Public methods available for client...
Confidential 34
Remote Contract
• Client can run on a different JVM
• It can be a web component, an application client, or...
Confidential 35
Remote Bean Declaration
• @Remote
public interface CalculationRemote {…}
@Stateless
public class Calculati...
Confidential 36
Using Session Beans in Clients
Client obtains Session Bean instances through:
 JNDI lockup (using the Jav...
Confidential 37
Portable JNDI Syntax
Three JNDI namespaces are used for portable JNDI lookups:
 java:global – remote bean...
Confidential 38
Lookup Example
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.en...
Confidential 39
Accessing Beans Using JNDI
• No-Interface view:
CalculationBean bean = (CalculationBean)
initialContext.lo...
Confidential 40
Accessing Beans Using Dependency Injection
• No-Interface view:
@EJB
private CalculationBean bean;
• Local...
Confidential 41
Ambiguous and overloaded EJB names
@Remote(GreetingService.class)
@Stateless(name="dailyGreetingBean")
pub...
Confidential 42
EJB Register in Deployment Descriptor Example
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>MyEJB</ejb-...
Confidential 43
Summary: client contracts
Remote Local No Interface View (Local)
Accessed by Interface
@Remote
Accessed by...
Confidential 44
Messaging and
Message-Driven
Beans
Confidential 45
JMS-Based Message-Driven Beans
Message-driven beans (MDBs) are stateless, server-side,
transaction-aware c...
Confidential 46
Activation Config Properties
• @MessageDriven(activationConfig={
@ActivationConfigProperty(
propertyName="...
Confidential 47
MessageListener interface
• javax.jms.MessageListener interface:
public interface MessageListener {
public...
Confidential 48
The Lifecycle of a Message-Driven Bean
• The Method-Ready Pool is
similar to the instance pool
used for st...
Confidential 49
References and
Injections
Confidential 50
Entity Manager Reference
• Entity Manager can be registered in the JNDI Context of an EJB
• EJB container ...
Confidential 51
Entity Manager Reference
• The @PersistenceContext annotation can also be placed on a
setter method or mem...
Confidential 52
Resource Reference
• JNDI Context can be used to look up external resources
• the external resources are m...
Confidential 53
Resource Reference Example
@Resource(name="jms/QueueConnectionFactory")
private javax.jms.QueueConnectionF...
Confidential 54
Transactions
Confidential 55
Java EE Transaction Concepts
 Atomicity – operations succeed or fail together
 Locking and isolation – o...
Confidential 56
Transaction Management Types
javax.ejb .TransactionManagement - specifies session or
message-driven bean t...
Confidential 57
Container-Managed Transactions
• Can be used with both of Session and Message-driven bean
types
• The cont...
Confidential 58
CMT: Transaction Attributes
Example: does method B execute with a new Transaction ?
A transaction attribut...
Confidential 59
Transaction Attributes values
Attribute Name Description
Required
(default)
The method becomes part of the...
Confidential 60
Container-Managed Transactions
• EntityManager should be accessed within the JTA transaction
Use Required,...
Confidential 61
Transaction Attribute example
@TransactionAttribute(NOT_SUPPORTED)
@Stateful
public class TransactionBean ...
Confidential 62
Bean-Managed Transactions
The JTA specification
 Obtain a reference to the UserTransaction object from
th...
Confidential 63
Using the begin, commit, and rollback methods
@Stateful
@TransactionManagement(TransactionManagementType.B...
Confidential 64
Exception
Handling
Confidential 65
Application and System Exceptions
 Application Exceptions - normally thrown in response to a
business-log...
Confidential 66
Handling System Exceptions
• EJB Container throws it when encounters an internal
application failure
• App...
Confidential 67
Handling System Exceptions
• If transaction is started, a system exception (thrown by the
enterprise bean ...
Confidential 68
Handling Application Exceptions
• Always delivered directly to the client without being
repackaged as an E...
Confidential 69
What next…
 Security in EJB
 EJB and Web Services
 Interceptors
 Timing Service
 Packaging and deploy...
Confidential 70
Ссылки
• EJB Oracle Tutorial:
http://docs.oracle.com/javaee/6/tutorial/doc/bnblr.html
• EJB Specification:...
Confidential 71
Спасибо за внимание
Сергей Болбин
Software developer
Skype sergey.bolbin
Sergey.Bolbin@returnonintelligenc...
Upcoming SlideShare
Loading in …5
×

Introduction to EJB

2,814 views

Published on

Webinar presentation http://www.returnonintelligence.ru/webinars/introduction-to-ejb/

Published in: Software
  • Be the first to comment

Introduction to EJB

  1. 1. Core Systems Transformation Solutions Enterprise Java Beans Overview. Part 1 October 15, 2015
  2. 2. Confidential 1 Agenda 1. Overview 2. Session Beans 3. Accessing Session Beans 4. Messaging and MDB 5. References and Injections 6. Transactions 7. Exception Handling
  3. 3. Confidential 2 Overview
  4. 4. Confidential 3 What is EJB ? Enterprise Java Beans • is platform for building portable, reusable, and scalable business applications using the Java • is Java components (classes) that executes in a specialized runtime environment called the EJB container
  5. 5. Confidential 4 Java EE Components
  6. 6. Confidential 5 EJB container functionality 5 Resources Client ClientSupport Lifecycle Management Resource Management EJB EJB EJB
  7. 7. Confidential 6 EJB Container Services EJB Container provides valuable services for enterprise application development: • Transactions support • Security model • Persistence support • Remote access • Web-services • Interceptors • Thread Safety and Concurrency control • Timing services & job scheduling • Messaging • Asynchronous interactions
  8. 8. Confidential 7 EJB Version History  EJB 1.1 (J2EE 1.2), 1999 – Session beans (stateful & stateless), Entity Beans – Remote interface  EJB 2.0 (J2EE 1.3), 2001 – Message Driven beans – Entity 2.x and EJB QL – Local & Remote Interfaces  EJB 2.1 (J2EE 1.4), 2003 – EJB Timer Service – EJB QL updates  EJB 3 (2006) , 3.1(2009), 3.2 (2013)
  9. 9. Confidential 8 Types of Enterprise Bean Objects • Session Beans • Message-driven beans • Entities
  10. 10. Confidential 9 Session Beans
  11. 11. Confidential 10 Session Beans • Performs specific business-logic operations • Managed by EJB Container • Available for a client session • Is removed when the EJB container crashes • Can be transaction-aware • Can be invoked either locally or remotely using Java RMI
  12. 12. Confidential 11 Session Beans Session bean object is not directly accessed Session EJB component has the following elements: • Component interface • Implementation class
  13. 13. Confidential 12 Types of Session Beans • Stateless Session Beans • Stateful Session Beans • Singleton Session Beans
  14. 14. Confidential 13 Stateless Session Bean • Does not retain client-specific information • A client might not get the same session bean instance • Can implement a web service • Any number of requests can be handled by the same instance
  15. 15. Confidential 14 Stateless Session Bean EJB EJB EJB EJB EJB Request Instance Pool EJB Container Random Selection
  16. 16. Confidential 15 Stateless Bean Lifecycle and Callbacks @Stateless public class CalculationBean { @PostConstruct void construct() { } @PreDestroy void destroy() { } public int sum(int a, int b) { return a + b; } }
  17. 17. Confidential 16 Stateless Session Bean Example @Local public interface CalculationLocal { int sum(int a, int b); } @Stateless public class CalculationBean implements CalculationLocal { public int sum(int a, int b) { return a + b; } }
  18. 18. Confidential 17 Stateful Session Bean • Supports conversation state • Is never shared, has only one client • Client can remove bean instance • Can be passivated by container • Cannot implement a web service
  19. 19. Confidential 18 Stateful Session Bean EJB id = 3 EJB id = 4 EJB id = 5 EJB id = 1 EJB id = 2 Request Instance Cache EJB Container Select by Session ID ID = 5
  20. 20. Confidential 19 Stateful Bean Lifecycle and Callbacks
  21. 21. Confidential 20 Stateful Bean Lifecycle and Callbacks (Example) @Stateful public class CalculationBean implements CalculationRemote { private int result = 0; @PostConstruct void construct(){} @PreDestroy void destroy(){} @PostActivate void activate(){} @PrePassivate void passivate(){} @Remove public void remove(){} public void add(int a) { result += a; } public int getResult() { return result; } }
  22. 22. Confidential 21 Singleton Session Bean • Instantiated once per application and exists for the lifecycle of the application • Only one bean per application (jvm) • Does not maintain state across server crashes/shutdowns • Supports concurrency requests • Can implement a web service • Perform tasks upon application startup and shutdown • State shared across the application
  23. 23. Confidential 22 Singleton Session Bean. Concurrency Management Singleton session beans are designed for concurrent access @javax.ejb.ConcurrencyManagement : - container-managed concurrency javax.ejb.ConcurrencyManagementType.CONTAINER - default - bean-managed concurrency javax.ejb.ConcurrencyManagementType.BEAN
  24. 24. Confidential 23 Container-Managed concurrency. Locking types Access locking types: javax.ejb.Lock, javax.ejb.LockType - @Lock(LockType.READ) - for read-only operations - @Lock(LockType.WRITE) - default; for exclusive access to the bean instance javax.ejb.AccessTimeout - annotation is used to specify the number of TimeUnits before an access timeout occurs
  25. 25. Confidential 24 Container-Managed Singleton Example @Singleton @ConcurrencyManagement(CONTAINER) @AccessTimeout(value=20, unit = TimeUnit.SECONDS) public class CalculationBean implements CalculationLocal { private Long result; @PostConstruct void construct() { result = 0L; } @Lock(LockType.WRITE) public void add(int a) { result += a; } @Lock(LockType.READ) @AccessTimeout(value=3600) public Long getResult() { return result; } }
  26. 26. Confidential 25 Initializing Singleton Session Beans @Startup @Singleton @DependsOn({"PrimaryBean", "SecondaryBean"}) public class CalculationBean implements CalcLocal, CalcRemote { private Long result; @PostConstruct void construct() { // any bean initialization ... result = 0L; } ……… } Eager Initialization: @javax.ejb.Startup @javax.ejb.DependsOn
  27. 27. Confidential 26 Singleton Session Beans. Errors Handling • If a singleton session bean encounters an error when initialized by the EJB container, that singleton instance will be destroyed • Singleton instance is not destroyed when methods causes system exceptions
  28. 28. Confidential 27 Summary: Session Bean Types Stateless Stateful Singleton Has no client association Each client has its own bean instance Instantiated once per application Has no state between calls Stores state between client calls Each client obtains single state Pooled in memory May be passivated to disk, cached - Client couldn’t manage lifecycle Removable by client Client couldn’t manage lifecycle Does not support concurrency Does not support concurrency Supports concurrency Implements WS Couldn’t implement WS Implements WS
  29. 29. Confidential 28 Accessing Enterprise Java Beans
  30. 30. Confidential 29 Accessing Session Beans  Access EJB through a no-interface view or business interface  no-interface view: invoke any public methods in the EJB class or superclasses  Business interface contains the business methods of the EJB  Session beans can have more than one business interface
  31. 31. Confidential 30 Session Bean Contracts EJB Contracts Local Remote (via Remote Interface) As Web Service Local Interface No-Interface view
  32. 32. Confidential 31 Local Interface Contract • Run in the same JVM as the EJB • Client: Web component or another enterprise bean • Supports pass-by-reference semantics • The local business interface defines the bean’s business methods
  33. 33. Confidential 32 Local Bean Declaration To build an enterprise bean that allows local access: @Local public interface CalculationLocal { … } @Stateless public class CalculationBean implements CalculationLocal { … } or public interface CalculationLocal { … } @Stateless @Local(CalculationLocal.class) public class CalculationBean implements CalculationLocal { … }
  34. 34. Confidential 33 Local Contracts. No-Interface view • No-interface view == local view • Public methods available for client access • The client and the target bean must be packaged in the same application (EAR) • @Stateless public class CalculationBean { … }
  35. 35. Confidential 34 Remote Contract • Client can run on a different JVM • It can be a web component, an application client, or another EJB • Supports pass-by-value semantics • Must implement a business interface • Requires creating a stub and a skeleton, which will cost cycles • Expensive taking time to transfer the object to the client and create copies (Serializable)
  36. 36. Confidential 35 Remote Bean Declaration • @Remote public interface CalculationRemote {…} @Stateless public class CalculationBean implements CalculationRemote {…} • Or decorate the bean class with @Remote: public interface CalculationRemote {…} @Remote(CalculationRemote.class) public class CalculationBean implements CalculationRemote {…} To create an enterprise bean that allows remote access:
  37. 37. Confidential 36 Using Session Beans in Clients Client obtains Session Bean instances through:  JNDI lockup (using the Java Naming and Directory Interface syntax to find the enterprise bean instance)  dependency injection (using annotations)
  38. 38. Confidential 37 Portable JNDI Syntax Three JNDI namespaces are used for portable JNDI lookups:  java:global – remote beans using JNDI java:global[/application name]/module name/enterprise bean name[!interface name]  java:module - local enterprise beans within the same module (JAR) java:module/enterprise bean name[!interface name]  java:app - local enterprise beans packaged within the same application (EAR) java:app[/module name]/enterprise bean name[!interface name]
  39. 39. Confidential 38 Lookup Example Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory"); … InitialContext initialContext = new InitialContext(props); CalculationLocal bean = (CalculationLocal) initialContext .lookup("java:app/myapp- ejb/CalculationBean!net.myapp.service.ejb.CalculationLocal");
  40. 40. Confidential 39 Accessing Beans Using JNDI • No-Interface view: CalculationBean bean = (CalculationBean) initialContext.lookup("java:module/CalculationBean"); • Local: CalculationLocal bean = (CalculationLocal) initialContext.lookup("java:module/CalculationBean! CalculationLocal"); • Remote: CalculationRemote bean = (CalculationRemote) initialContext.lookup("java:global/myapp/myapp- ejb/CalculationBean!CalculationRemote");
  41. 41. Confidential 40 Accessing Beans Using Dependency Injection • No-Interface view: @EJB private CalculationBean bean; • Local: @EJB private CalculationLocal bean; • Remote: @EJB private CalculationRemote bean;
  42. 42. Confidential 41 Ambiguous and overloaded EJB names @Remote(GreetingService.class) @Stateless(name="dailyGreetingBean") public class DailyGreeting implements GreetingService { } @Remote(GreetingService.class) @Stateless(name="weeklyGreetingBean") public class WeeklyGreeting implements GreetingService { } Client: @Remote(GreetingManager.class) @Stateless public class GreetingManagerImpl implements GreetingManager { @EJB(beanName ="ejbModule.jar#dailyGreetingBean") GreetingService greetingService; }
  43. 43. Confidential 42 EJB Register in Deployment Descriptor Example <ejb-jar> <enterprise-beans> <session> <ejb-name>MyEJB</ejb-name> <ejb-local-ref> <ejb-ref-name>org.examples.MyEJBBean/otherBean </ejb-ref-name> <ejb-ref-type>Session</ejb-ref-type> <local>org.examples.MyEJB2LocalBusiness</local> <ejb-link>MyEJB2</ejb-link> </ejb-local-ref> </session> </enterprise-beans> </ejb-jar> @Stateful(name="MyEJB") public class MyEJBBean implements MyEJBLocalBusiness { @EJB // Field-level injection private MyEJB2LocalBusiness otherBean; }
  44. 44. Confidential 43 Summary: client contracts Remote Local No Interface View (Local) Accessed by Interface @Remote Accessed by Interface @Local Public methods available for client access Could be accessed from another JVM Accessed from the same JVM Accessed from the same EAR Supports pass-by-value semantics Supports pass-by- reference semantics Supports pass-by- reference semantics JNDI Lookup or DI (from the same JVM only) JNDI Lookup or DI JNDI Lookup or DI
  45. 45. Confidential 44 Messaging and Message-Driven Beans
  46. 46. Confidential 45 JMS-Based Message-Driven Beans Message-driven beans (MDBs) are stateless, server-side, transaction-aware components for processing asynchronous messages delivered via JMS • Able to use all EJB components environment: transactions, security, resources, concurrency and message acknowledgment • Does not have a business or component interface • Identified using the @javax.ejb.MessageDriven annotation or deployment descriptor
  47. 47. Confidential 46 Activation Config Properties • @MessageDriven(activationConfig={ @ActivationConfigProperty( propertyName="destinationType", propertyValue="javax.jms.Queue"), @ActivationConfigProperty( propertyName = "destination", propertyValue = "ResourceQueueName"), @ActivationConfigProperty( propertyName="messageSelector", propertyValue="MessageFormat = 'Version 3.4'"), @ActivationConfigProperty( propertyName="acknowledgeMode", propertyValue="Auto-acknowledge")}) public class ReservationProcessorBean implements javax.jms.MessageListener { @Override public void onMessage(Message var1) {...} }
  48. 48. Confidential 47 MessageListener interface • javax.jms.MessageListener interface: public interface MessageListener { public void onMessage(Message message); } • onMessage() Is called, when message arrives • onMessage() is finished -> MDB ready to process other message • MDBs can integrate with other messaging systems
  49. 49. Confidential 48 The Lifecycle of a Message-Driven Bean • The Method-Ready Pool is similar to the instance pool used for stateless beans • When an MDB instance is in the Does Not Exist state, it has not been instantiated yet • Callbacks : @PostConstruct, @PreDestroy
  50. 50. Confidential 49 References and Injections
  51. 51. Confidential 50 Entity Manager Reference • Entity Manager can be registered in the JNDI Context of an EJB • EJB container has full control over the lifecycle of the underlying persistence context of the Entity Manager • @javax.persistence.PersistenceContext can be used on bean class’s setter methods or member fields or directly on the class
  52. 52. Confidential 51 Entity Manager Reference • The @PersistenceContext annotation can also be placed on a setter method or member field : @Stateless public class CalculationBean implements CalculationLocal { @PersistenceContext(unitName="MyDB") private EntityManager em; }
  53. 53. Confidential 52 Resource Reference • JNDI Context can be used to look up external resources • the external resources are mapped into a name within the JNDI Context by using annotations or DD xml content • External Resources: javax.sql.DataSource javax.jms : Queue, Topic, Connection Factories javax.mail.Session java.net.URL java.lang: String, Character, Byte, Short, Integer, Long, Boolean, Double, Float, Class, and all Enum types. Javax.transaction: UserTransaction, TransactionSynchronizationRegistry CORBA ORB references JPA PersistenceUnit and PersistenceContext
  54. 54. Confidential 53 Resource Reference Example @Resource(name="jms/QueueConnectionFactory") private javax.jms.QueueConnectionFactory queueConnectionFactory; @Resource(name="jms/someQueue") private javax.jms.Queue queue; @Resource( name="jdbc/PostgresDB", type=javax.sql.DataSource.class, shareable = true, authenticationType = AuthenticationType.APPLICATION) private javax.sql.DataSource dataSource;
  55. 55. Confidential 54 Transactions
  56. 56. Confidential 55 Java EE Transaction Concepts  Atomicity – operations succeed or fail together  Locking and isolation – only one transaction at a time can update a particular piece of data  Flat transaction model – only one transaction is in effect in a particular thread at any given time. A transaction cannot be made up of subtransactions
  57. 57. Confidential 56 Transaction Management Types javax.ejb .TransactionManagement - specifies session or message-driven bean transaction management type: @TransactionManagement(value = TransactionManagementType.CONTAINER) – default @TransactionManagement(value = TransactionManagementType.BEAN)
  58. 58. Confidential 57 Container-Managed Transactions • Can be used with both of Session and Message-driven bean types • The container begins a transaction before method starts and commits before the method exits • Each method can be associated with a single transaction • Do not require all methods to be associated with transactions • Nested or multiple transactions are not allowed within a method • Bean must not use : - java.sql.Connection commit(), rollback(), setAutoCommit(); - javax.jms.Session commit(), rollback(); - javax.transaction.UserTransaction interface
  59. 59. Confidential 58 CMT: Transaction Attributes Example: does method B execute with a new Transaction ? A transaction attribute controls the scope of a Transaction @javax.ejb.TransactionAttribute
  60. 60. Confidential 59 Transaction Attributes values Attribute Name Description Required (default) The method becomes part of the caller’s transaction. If the caller does not have a transaction, the method runs in its own RequresNew The method always runs in its own transaction. Any existing transaction is suspended NotSupported The method never runs in a transaction. Any existing transaction is suspended Supports The method becomes part of the caller’s transaction if there is one. If the caller does not have a transaction, the method does not run in a transaction Mandatory It is an error to call this method outside of a transaction Never It is an error to call this method in a transaction
  61. 61. Confidential 60 Container-Managed Transactions • EntityManager should be accessed within the JTA transaction Use Required, RequiresNew and Mandatory type • MDB only the NotSupported or Required transaction attribute • The Mandatory transaction attribute cannot be used with EJB endpoints • The persistence context is propagated between EJB invocations in the same transaction
  62. 62. Confidential 61 Transaction Attribute example @TransactionAttribute(NOT_SUPPORTED) @Stateful public class TransactionBean implements Transaction { ... @TransactionAttribute(REQUIRES_NEW) public void firstMethod() {...} @TransactionAttribute(REQUIRED) public void secondMethod() {...} public void thirdMethod() {...} public void fourthMethod() {...} }
  63. 63. Confidential 62 Bean-Managed Transactions The JTA specification  Obtain a reference to the UserTransaction object from the container  Scope the transactions using the begin and commit Methods  Fail a transaction using the rollback method
  64. 64. Confidential 63 Using the begin, commit, and rollback methods @Stateful @TransactionManagement(TransactionManagementType.BEAN) public class CalculationBean implements CalculationLocal { @Resource UserTransaction ut; public void calculate(…) throws SystemException { try { ut.begin(); // Transaction starts here //... transaction operation 1, 2, 3 ut.commit(); // Transaction finishes here } catch (Exception e) { ut.rollback(); // Oops: roll back } } }
  65. 65. Confidential 64 Exception Handling
  66. 66. Confidential 65 Application and System Exceptions  Application Exceptions - normally thrown in response to a business-logic error  System Exceptions - java.lang.RuntimeException and its subclasses
  67. 67. Confidential 66 Handling System Exceptions • EJB Container throws it when encounters an internal application failure • Application throws it to abort business process • Subclasses: EJBException, EJBTransactionRolledBackexception • Always cause a transaction to roll back • The container handles automatically : 1. Roll back the transaction 2. Log exception 3. Discard EJB instance
  68. 68. Confidential 67 Handling System Exceptions • If transaction is started, a system exception (thrown by the enterprise bean method) will be caught by the container and rethrown as an EJBTransactionRolledbackException • If the client did not propagate a transaction to the EJB, the system exception will be caught and rethrown as an EJBException
  69. 69. Confidential 68 Handling Application Exceptions • Always delivered directly to the client without being repackaged as an EJBException type • By default, does not cause a transaction to roll back • To force application Exception to transaction roll back @javax.ejb.ApplicationException @ApplicationException(rollback = true) public class MyException extends Exception { ... } • Can be used with checked and unchecked exceptions, exception will not be wrapped into EJBException
  70. 70. Confidential 69 What next…  Security in EJB  EJB and Web Services  Interceptors  Timing Service  Packaging and deployment  Vendor-Specific features  Testing and Mock Containers
  71. 71. Confidential 70 Ссылки • EJB Oracle Tutorial: http://docs.oracle.com/javaee/6/tutorial/doc/bnblr.html • EJB Specification: http://oracle.com/technetwork/java/docs-135218.html
  72. 72. Confidential 71 Спасибо за внимание Сергей Болбин Software developer Skype sergey.bolbin Sergey.Bolbin@returnonintelligence.com

×