7 min read

Enterprise JavaBeans 3.2

The Enterprise JavaBeans 3.2 Specification was developed under JSR 345. This section just gives you an overview of improvements in the API. The complete document specification (for more information) can be downloaded from http://jcp.org/aboutJava/communityprocess/final/jsr345/index.html.

The businesslayer of an application is the part of the application that islocated between the presentationlayer and data accesslayer. The following diagram presents a simplified Java EE architecture. As you can see, the businesslayer acts as a bridge between the data access and the presentationlayer.

It implements businesslogic of the application. To do so, it can use some specifications such as Bean Validation for data validation, CDifor context and dependency injection, interceptors to intercept processing, and so on. As thislayer can belocated anywhere in the network and is expected to serve more than one user, it needs a minimum of non functional services such as security, transaction, concurrency, and remote access management. With EJBs, the Java EE platform provides to developers the possibility to implement thislayer without worrying about different non functional services that are necessarily required.

In general, this specification does not initiate any new major feature. It continues the work started by thelast version, making optional the implementation of certain features that became obsolete and adds slight modification to others.

Pruning some features

After the pruning process introduced by Java EE 6 from the perspective of removing obsolete features, support for some features has been made optional in Java EE 7 platform, and their description was moved to another document called EJB 3.2 Optional Features for Evaluation. The features involved in this movement are:

  • EJB 2.1 and earlier Entity Bean Component Contract for Container-Managed Persistence
  • EJB 2.1 and earlier Entity Bean Component Contract for Bean-Managed Persistence
  • Client View of EJB 2.1 and earlier Entity Bean
  • EJB QL: Querylanguage for Container-Managed Persistence Query Methods
  • JAX-RPC-based Web Service Endpoints
  • JAX-RPC Web Service Client View

The latest improvements in EJB 3.2

For those who have had to use EJB 3.0 and EJB 3.1, you will notice that EJB 3.2 has brought, in fact, only minor changes to the specification. However, some improvements cannot be overlooked since they improve the testability of applications, simplify the development of session beans or Message-Driven Beans, and improve control over the management of the transaction and passivation of stateful beans.

Session bean enhancement

A session bean is a type of EJB that allows us to implement businesslogic accessible tolocal, remote, or Web Service Client View. There are three types of session beans: stateless for processing without states, stateful for processes that require the preservation of states between different calls of methods, and singleton for sharing a single instance of an object between different clients.

The following code shows an example of a stateless session bean to save an entity in the database:

@Stateless public class ExampleOfSessionBean { @PersistenceContext EntityManager em; 

public void persistEntity(Object entity){ em.persist(entity); }}

Talking about improvements of session beans, we first note two changes in stateful session beans: the ability to executelife-cycle callback interceptor methods in a user-defined transaction context and the ability to manually disable passivation of stateful session beans.

It is possible to define a process that must be executed according to thelifecycle of an EJB bean (post-construct, pre-destroy). Due to the @TransactionAttribute annotation, you can perform processes related to the database during these phases and control how they impact your system. The following code retrieves an entity after being initialized and ensures that all changes made to the persistence context are sent to the database at the time of destruction of the bean. As you can see in the following code, TransactionAttributeType of init() method is NOT_SUPPORTED; this means that the retrieved entity will not be included in the persistence context and any changes made to it will not be saved in the database:

@Stateful public class StatefulBeanNewFeatures { 

@PersistenceContext(type= PersistenceContextType.EXTENDED) EntityManager em; 

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) 

@PostConstruct public void init(){ entity = em.find(...); } 

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) 

@PreDestroy public void destroy(){ em.flush(); } }

The following code demonstrates how to control passivation of the stateful bean.

Usually, the session beans are removed from memory to be stored on the disk after a certain time of inactivity. This process requires data to be serialized, but during serialization all transient variables are skipped and restored to the default value of their data type, which is null for object, zero for int, and so on. To prevent theloss of this type of data, you can simply disable the passivation of stateful session beans by passing the false value to the passivationCapable attribute of the @Stateful annotation.

@Stateful(passivationCapable = false) public class StatefulBeanNewFeatures { //... }

For the sake of simplicity, EJB 3.2 has relaxed the rules to define the defaultlocal or remote business interface of a session bean. The following code shows how a simple interface can be considered aslocal or remote depending on the case:

//In this example, yellow and green are local interfaces public interface yellow { … } public interface green { … } @Stateless public class Color implements yellow, green { … } //In this example, yellow and green are local interfaces public interface yellow { … } public interface green { … } @Local @Stateless public class Color implements yellow, green { … } //In this example, yellow and green are remote interfaces public interface yellow { … } public interface green { … } @Remote @Stateless public class Color implements yellow, green { … } //In this example, only the yellow interface is exposed as a remote interface @Remote public interface yellow { … } public interface green { … } @Stateless public class Color implements yellow, green { … } //In this example, only the yellow interface is exposed as a remote interface public interface yellow { … } public interface green { … } @Remote(yellow.class) @Stateless public class Color implements yellow, green { … }

EJBlite improvements

Before EJB 3.1, the implementation of a Java EE application required the use of a full Java EE server with more than twenty specifications. This could be heavy enough for applications that only need some specification (as if you were asked to take a hammer to kill a fl y). To adapt Java EE to this situation, JCP (Java Community Process) introduced the concept of profile and EJBlite. Specifically, EJBlite is a subset of EJBs, grouping essential capabilities forlocal transactional and secured processing. With this concept, it has become possible to make unit tests of an EJB application without using the Java EE server and it is also possible to use EJBs in web applications or Java SE effectively.

In addition to the features already present in EJB 3.1, the EJB 3.2 Specification has added support forlocal asynchronous session bean invocations and non persistent EJB Timer Service. This enriches the embeddable EJBContainer, web profiles, and augments the number of testable features in an embeddable EJBContainer. The following code shows an EJB packaged in a WAR archive that contains two methods. The asynchronousMethod() is an asynchronous method that allows you to compare the time gap between the end of a method call on the client side and the end of execution of the method on the server side. The nonPersistentEJBTimerService() method demonstrates how to define a non persistent EJB Timer Service that will be executed every minute while the hour is one o’clock:

@Stateless public class EjbLiteSessionBean { 

@Asynchronous public void asynchronousMethod()

{ try{ System.out.println("EjbLiteSessionBean - start : "+new Date()); 

Thread.sleep(1000*10); System.out.println("EjbLiteSessionBean - end : "+new Date()); }catch

(Exception ex){ ex.printStackTrace(); } } 

@Schedule(persistent = false, minute = "*", hour = "1") 

public void nonPersistentEJBTimerService()

{ System.out.println("nonPersistentEJBTimerService method executed"); } }

Changes made to the TimerService API

The EJB 3.2 Specification enhanced the TimerService APiwith a new method called getAllTimers(). This method gives you the ability to access all active timers in an EJB module. The following code demonstrates how to create different types of timers, access their information, and cancel them; it makes use of the getAllTimers() method:

@Stateless public class ChangesInTimerAPI implements ChangesInTimerAPILocal 

{ @Resource TimerService timerService; public void createTimer()

{ //create a programmatic timer long initialDuration = 1000*5; 

long intervalDuration = 1000*60; String timerInfo = "PROGRAMMATIC TIMER"; 

timerService.createTimer(initialDuration, intervalDuration, timerInfo); } 

@Timeout public void timerMethodForProgrammaticTimer()

{ System.out.println("ChangesInTimerAPI - programmatic timer : "+new Date()); } 

@Schedule(info = "AUTOMATIC TIMER", hour = "*", minute = "*") 

public void automaticTimer(){ System.out.println("ChangesInTimerAPI - automatic timer : "+new 

Date()); } public void getListOfAllTimers(){ Collection alltimers = timerService.getAllTimers(); 

for(Timer timer : alltimers){ System.out.println("The next time out : "+timer. 

getNextTimeout()+", " + " timer info : "+timer.getInfo()); timer.cancel(); } } }

In addition to this method, the specification has removed the restrictions that required the use of javax.ejb.Timer and javax.ejb.TimerHandlereferences only inside a bean.


Subscribe to the weekly Packt Hub newsletter. We'll send you the results of our AI Now Survey, featuring data and insights from across the tech landscape.

* indicates required

LEAVE A REPLY

Please enter your comment!
Please enter your name here