j2ee‎ > ‎

J2ee Transaction

posted Jun 20, 2010, 7:25 PM by Kuwon Kang

Last Minute Refresher Notes for SCBCD 5.0 - Raghavendra Balgi
1. These have been picked up from the specs and I'am not responsible for any minor goof-ups.
Tread carefully;-)
2. Highly disorganised, and there might be some reptitions along the way
3. Pls enhance/modify as required

1. Message driven bean can use REQUIRED, NOT_SUPPORTED

2. Bean managed transactions can only be used for message driven beans and session beans.
3. while using BMT do not use setRollbackOnly and getRollbackOnly from EJBContext. Instead
use getStatus() method from UserTransaction or rollback using rollback() method.
4. Transactions are available to business method,message listener methods, timeout methods
and interceptor methods.
5. If a stateless session bean doesnt commit/rollback the transaction the container will
mark the transaction for rollback and send a EJBException to the client
6. CMT Transaction attribute -
1. REQUIRED - new created if one doesnt already exist
2. REQUIRES_NEW - always creates new (existing suspended)
3. NEVER - If exists returns EJBException
4. SUPPORTS - If exists uses it else doesnt bother to create new
5. NOT_SUPPORTED - current trns if exists is suspended before invoking the method
6. MANDATORY - If none exists returns EJBTransactionRequiredException
(EJBTransactionRequiredLocalException for 2.1 using local interface)
7. Beans using CMT shouldnt use UserTransaction Interface
8. deployment descriptor cannot be used to override the transaction-type associated with the bean
9. deafult transaction attribute is REQUIRED and default transaction-type is CONTAINER
10. example deployment descriptor entry for a bean with transaction details








11. CMT stateful beans can implement SessionSychronization interface (afterBegin(),beforeCompletion() and
afterCompletion() methods)

Applcation Exceptions
1. Application Exception may be specified on the business interface,message listener method or the webservice
2. Application Exception may subclass java.lang.Exception or java.lang.RuntimeException but not
3. javax.ejb.CreateException,FinderException,RemoveException are treated as Application Exceptions
4. An Application Exception is passed to the client as-is
5. An application exception will not cause transaction roll-back (unless specified by the rollback
element of @ApplicationException annotation)



6. A system exception is an exception that is subclass of RemoteException or a RuntimeException which is
not defined as a Application Exception

1. Session bean with REQUIRED/MANDATORY/SUPPORTS (clients transaction) throws ApplicationException, client receives ApplicationException
2. Session bean with REQUIRED/MANDATORY/SUPPORTS (clients transaction) throws non-ApplicationException, client receives EJBTransactionRolledbackException
2. Session bean with REQUIRED/REQUIRES_NEW (container transaction) throws ApplicationException, client receives ApplicationException
3. Session bean with REQUIRED/REQUIRES_NEW (container transaction) throws non-ApplicationException, client receives EJBException (discard-instance)
3. No transaction, throws ApplicationException, client receives application exception.
4. No transaction, throws non-ApplicationException, client receives EJBException (discard instance).
2. Session bean (2.1 or as a webservice endpoint) with REQUIRED/MANDATORY/SUPPORTS (clients Transaction) throws non-ApplicationException, client receives EJBTransactionRolledbackException (or EJBTransactionRolledbackLocalException if local client) (discard instance)

1. A bean can implement TimedObject and implement ejbTimeout(Timer) method or annotate a method as @Timeout (public void method(Timer))
to specify a timeout callback.
2. createTimer() methods from TimerService also specify duration in milliseconds.

1. getCallerPrincipal() and isCallerInRole(String) of the EJBContext are used for programmatic security


or use @DeclareRoles("")










Here, role-link should be one of the roles defined by security-role or specified by DeclareRoles annotation.


1. EntityManager is associated with a pesistence context (within which a set of entity instances are managed)
2. set of instances managed by a EntityManager is defined by a persistence unit.
3. EntityTransaction getTransaction();public void persist(Object);public void remove(Object);public void refresh(Object);
public Object merge(Object);public void lock(Object,LockModeType) -READ/WRITE
4. When transactions holding write locks are commited the version field of the entities managed are incremented.
5. merge only works within a transaction
6. public 
T find (Class,Object) (null if doesnt exist)
7. public 
T getReference (Class,Object) (EntityNotFoundException if doesnt exist on access) - returns hollow enbtities;doesnt access database;loaded on access
8. public boolean contains(Object) - true if entity part of the persistance context
9. public void flush() - requires transaction - throws TransactionRequiredException if one doesnt exist
10. set/get FlushModeType - AUTO or COMMIT
11. public void clear() - all managed entities are detached and ends the peristance context
12. createQuery();createNamedQuery();createNativeQuery()
13. public boolean isOpen();public void close()
14. persist;merge;refresh;remove methods require a transaction context

Lifecycle callbacks on Entities
1. Can be specified in the entity class, a mapped superclass or a seperate entity-listener class
2. @PrePersist,@PostPersist,@PreRemove,@PostRemove,@PreUpdate,@PostUpdate and @PostLoad
3. default entity listeners are specified for all entities in a persistence unit
4. multiple entity listeners can be specified on the entity class or mapped superclass and order of
invocation is the order in which they are specified in the metadata.
5. defined directly on the entity class or mapped superclass (void methodname())
6. defined in a Entity-listener class (void methodname(Object)) - the object here is the entity on which
the operation is being performed.
7. @EntityListeners ia the annotation to define entity-listeners for a Entity (takes an array as input)

Operation Allowed - Session Beans
dependency injection methods - getEJBHome(),getEJBLocalHome()
lifecycle callbacks(PostConstruct/PostDestroy) - getBusinessObject,getEJBHome, getEJBLocalHome,

business method (or business interceptor method) - getBusinessObject,getEJBHome, getEJBLocalHome,
getCallerPrincipal,isCallerInRole, getRollbackOnly,
set-RollbackOnly, getEJBObject, getEJBLocalObject,
timer callbacks - same as above

*getInvokedBusinessInterface is only accessible in business methods or business interceptor methods
*Stateless beans with BMT will also have access to getUserTransaction() method in all but DI methods (and
will not have access to setRollbackOnly() and getRollbackOnly())

IN stateful beans, the lifecycle call back methods have access to RM's, EM/EMF and Enterprise beans.
(as they are executed in a transactional context)

Message Driven Beans
DI Methods - lookup() of MessageDrivenContext
lifecycle callbacks - getTimerService(),lookup()
message listener method/interceptors - getRollbackOnly, setRollbackOnly,getCallerPrincipal,
getTimerService,lookup,RM,Enterprise Beans,EMF/EM,Timer
callbacks - same as above
* Should never call isCallerInRole(),getEJBObject(),getEJBLocalObject()

Session Beans Contract
Bean Provider - Bean class, local and local home/remote and remote home in case of 2.1 clients, business interfaces (3.0)
and any other interceptor classes.
Bean Class - public, non-final,non-abstract
- public no-arg constructor
- no finalize() method
If a session bean implements a single interface, that interface will be considered as the local business interface.

1. Can be created for stateless session beans,message driven beans and 2.1 entity beans
2. javax.ejb.TimerService via DI or context.getTimerService()
3. Methods - createTimer() (4 variations) and getTimers() - duration is in millisecs
4. Can provide a method with @Timeout annotation (void method(Timer))or implement javax.ejb.TimedObject and provide
public void ejbTimeout(Timer) method
5. Op on expired Timer - NoSuchObjectLocalException
6. Methods on Timer - cancel(),getInfo() -> Serializable,getTimeRemaining()->long,getNextTimeout()->Date,
(TimerHandle has getTimer() method)
7. If transaction is rolled back, transaction is rolled back
8. If timer was cancelled and transaction rolled back then, the cancel is rescinded.
9. Timers are transaction aware.
10. A TimerHandle can be persisted
11. A timeout method can have any visibility but cannot be static or final.

1. entity class must be annotated by @Entity or via XML descriptor
2. Should have zero arg constructor with public/protected visibility
3. should not be final (none of the methods should be final)
4. persistent state variables should be private/protected or package
5. property accessor methods should be public or protected

1. @PreUpdate and @PostLoad are complementary to each other
2. @ExcludeDefaultListeners to exclude default listeners
3. Use @ExcludeSuperclassListeners to prevent invocation of superclass listeners for the entity class and
its subclasses
4. A entity can override the listener defined in the superclass
5. Listener methods in Listener Class - void method(Object) and void method() within the entity or mapped superclass
5. Order of Invocation for Listeners -
i) Default Listeners if any for the persistence unit
ii) Entity Listener of parent (mapped superclass)
iii) Entity Listener of entity
iv) Listeners defined in the parent
v) Listeners defined in the entity

1. PersistentContextType - TRANSACTION or EXTENDED
TransactionType - JTA (deafult in EE)/RESOURCE_LOCAL (default in SE)
2. NoResultException and NoUniqueResultException will not cause the current transaction
to be rolled back
3. If EntityTransaction.commit() fails - RollbackException
4. EntityExistsException - during persist() op
5. EntityNotFoundException - during getReference() or refresh() op.

1. Aggregate function in JPQL - AVG,COUNT,MIN,MAX,SUM
2. COUNT returns long
MIN/MAX retun the type that they were applied to
AVG returns double
SUM returns Long,Double or BigInteger or BigDecimal
COUNT returns zero when no values are found other return NULL

Managing Object Relationships
1. Use @SecondaryTable(name,pkJoinColumns=@PrimaryKeyJoinColumn(name)) to create split a single table
into two.
One to One Relationship
1. Use a @JoinColumn(name,referencedColumnName) annotation - name is the name of the column in the current table
and referenced column name is the name of the foreign key in the other table
This annotation will reside in the table that has the foreign key (primary key in the other table).
2. A bidirectional relationship will have a mappedBy on the OneToOne annotation on the secondary table
3. Use the @PrimaryKeyJoinColumn(name,referencedColumnName) if two table share a single key (primary of one table
becomes the primary of the second table which also acts as a foriegn key linking the two tables)

One To Many and Many To One Relationship
1. Use the @JoinColumn annotation on the many side of the relationship and a mappedBy on the other
side of the relationship for a bideirectional relationship
2. ManyToOne doesnt have mappedBy element for a simple reason that Many side is always the owning
side of the relationship

Many To Many Relationship
1. Should use a association table
2. Use a @JoinTable annotation on the owning side of the relationship (an arbitarry choice)
3. Use a mappedBy element of the ManyToMany relationship for a bdirectional relationship.

1. Cannot mix named and positional parameters
2. Inner Joins are default joins.
3. Left Join (is Left Outer Join) gets entities where values may be absent
4. Join fetch is useful in prefetching
5. _ stands for a single character and % stands for a group of characters in a literal string
6. ALL/ANY/SOME/EXISTS (subquery)
7. CONCAT/SUBSTRING/TRIM/LOWER/UPPER/LOCATE(locate_this,in_this,from_pos)

query="SELECT c FROM Customer c WHERE c.name LIKE :custName"


@EntityResult(entityClass=com.acme.Order.class, fields={
@FieldResult(name="id", column="order_id"),
@FieldResult(name="quantity", column="order_quantity"),
@FieldResult(name="item", column="order_item")}),

Bean Provider Responsibilities
1. creates the ejb-jar file
2. implements the business interfaces and the client view interfaces

Application Assembler Responsibilities

1. composes the application (ejb's) with other components
2. May modify the following
1. values of environment entries
2. description fields (can add new)
3. modify relationship names for 2.1 entity beans
4. further restrict the value of messageSelector activationConfigProperty
5. Bind enterprise beans references (using ejb-link)
6. Link message destination references
7. define security roles/link security role references
8. security idenntity
9. transaction attributes
10. override/augment/reorder interceptors

Cannot Modify:
1. beans Abstract schema name
2. Role source element

Deployer Responsibilities
1. Resolves external dependencies required by the EJB
2. Uses tools provided by the Container Provider
3. Maps security roles defined by the Bean Provider/Assembler to actual roles in the
operational environment

EJB Server Provider Responsibilities
1. Provides deployment tools necesary for the deployment of EJB's
2. Runtime support for deployed enterprise beans
3. Provides tools to the sysad to monitor rnutime behavior of installed beans

1. Managed persistence classes many be included in the root of the persistence unit
2. Specified by reference by naming classes/class archives or mapping xml files
3. provider/jta-data-source/mapping-file/jar-file/class/exclude-unlisted-classes and properties
4. Mapping file may be included in the META-INF of the persistence unit or in META-INF of any
jar file referenced in the persistence.xml file
5. jar files are specified relative to the root of the persistence unit

1. DeclareRoles and RunAs applies only to Types
2. DenyAll applies only to methods

Notes from Simplified Spec
1. If a bean implements more than one business interface then it needs to be specified as @Local
or @Remote
2. The same business interface canot be both Local and Remote
3. A business interface cannot extends javax.ejb.EJBObject or javax.ejb.EJBLocalObject
4. The bean class itself can be specified as @Local or @Remote (or both with a list of interfaces)
5. Methods of the business interface should not throw RemoteException
6. callback interceptor methods can have any visibility but shouldnt be final or static
7. a single callback cannot be specified more than once on a class
8. @AroundInvoke should always call InvocationContext.proceed()
9. business method interceptor - public Object method(InvocationContext) throws Exception
10. InvocationContext supports - getTarget(),getMethod(),get/setParamters(),getContextData() and proceed()
11. business interface for a MDB is the message listener interface (javax.jms.MessageListener)

Message Driven Beans
1. Asynchronous Message Consumers

JMS Primer
- create a Connection from a Fcatory
- create a Session from a Connection
- create a MessageProducer from the Session
- create a message
- producer.send(message)
- Connection.close()

- A message contains headers and a body
- MessageType - TextMessage,MapMessage,ObjectMessage,BytesMessage,StreamMessage
- create a message consumer on the session (Session.createMessageConsumer())
- consumer.setMessageListener(Object) - Object implements the MessageListener interface

Messaging Models
- Point to Point - One to One - Pull based (uses Queue)
- Publish/Subscribe - One to Many - Push (uses Topic)

Example Property Names - destinationType
- durability is one for Topics
- Auto-Acknowledge (container should tell the provideer about the delivery immediately)
- Dups-ok-acknowledge (container can tell the provideer anytime after message has been dispatched to a instance)

1. The transient fields in a SFSB is not set to default values upon activation (like deserialization). It can
contain arbitrary value
2. Nested stateful session beans share the same persistent context (if both use EXTENDED types). This applies
only if the contained interface is local and not remote
3. Application server managed EntityManagers (injected by annotation/xml) are transaction scoped
4. persistence.xml should be located with META-INF of :
1. classpath of a SE application
2. ejb-jar file
3. jar file of a WEB-INF/lib in a war
4. JAR file in the root of EAR file
5. JAR file in EAR lib dir
5. transaction type defaults to JTA in EE and RESOURCE_LOCAL in SE environments
6. The set of entities managed by a persistence unit will include
- Classes annotated with @Entity in the persistence.xml file's JAR file (unless
is specified)
- Classes annotated with @Entity that are contained within any JARs listed with
- Classes mapped in the META-INF/orm.xml file (if exists)
- Classes mapped in any XML files referenced with the
- Classes listed with any 
8. EJBAccessException is thrown when a certain user doesnt have access to execute a certain
method on a bean
10. method-intf can be used in the method element to specify which interface of the bean the
method belongs while applying security permissions
- Allowed values for method-intf - Remote,Home,LocalHome,Local,ServiceEndpoint