Business Tier

Business Tier Technologies

Enterprise JavaBeans

Enterprise JavaBeans is a server-side component model. Enterprise applications are built from distributed beans, whose management and life-cycle is handled by the EJB container. Beans are designed to be accessed as remote objects, but also support local interfaces for optimal performance.

Beans are always guaranteed to be thread-safe. Beans are pooled, and never have more than one client at a time.

Stateful session beans Maintains a conversational state as a “session”. State is retained for the duration of the client-bean session.
Stateless session beans Stateless beans do not maintain any conversational state from previous invocations. Beans are pooled to maintain thread-safety, but stateless beans provide better performance and scalability than stateful beans. Stateless beans may have instance variables, whose value will be retrained for use on subsequent calls, but the clients cannot rely on these variables for “session” type processing.
Message driven beans Supports asynchronous processing of JMS messages. Message driven beans are similar to stateless session beans, in that they never assume a conversational state.
Entity beans Beans that are persisted to a database. Entity beans will survive server shutdowns and crashes. Entity beans are part of the J2EE spec, and are no longer considered EJBs in version 3. In EJB v3, persistence is handled by JPA.

EJB interceptors

EJB 3 introduces a mechanism of Interceptors which provide some Aspect Oriented Programming tools for session beans and message driven beans. Interceptors can be associated to specific EJB method calls or to all method calls within an EJB class. There can be default interceptors that apply to all EJB methods on all EJBs in a web application. Interceptors can also be attached to lifecycle events in EJBs, such as @PostConstruct, @PreDestroy, @PrePassivate, and @PostActivate.

Interceptors can be attached using annotations or the XML deployment descriptors.

Methods within the interceptor class take an argument of type InvocationContext. Interceptor methods are annotated to indicate if they are triggered by lifecycle events or are invoked around EJB method calls.

EJB timer service

EJB 3 includes a timer service for executing time delayed and recurring operations. Timer schedules are persistent and will survive a crash or restart of the application server. Timers can execute callbacks on stateless session beans and message driven beans, but not on stateful beans.

Timer callback methods are marked by the @Timeout annotation or via the deployment descriptor or with the TimedObject interface. Timers are scheduled with the TimerService object which can be injected or retrieved from the EJBContext.

EJB transactions

Operations within EJBs are usually wrapped in ACID transactions. Transaction management support in JEE is provided by the Java Transaction API (JTA). Transactions control changes made through JDBC and JMS. There are two abstractions over JTA: Bean Managed Transactions and Container Managed Transactions. Unless we specify otherwise, JEE will use the CONTAINER abstraction.

Bean Managed Transactions (BMT) require the programmer to explicitly manage transactions through the UserTransaction interface. The UserTransaction can be assigned to a variable using @Resource dependency injection, or retrieved using JNDI, or can be created from the EJBContext. Operations on the UserTransaction include begin(), commit(), and rollback().

With Container Managed Transactions (CMT), the container will start, commit, or rollback transactions on our behalf. The rules for managing these transactions may be set by annotations or in the EJB deployment descriptor. The default mode is that transactions are REQUIRED, in which a transaction is created when an EJB method is first called and then committed when it is completed. If the initial EJB calls other EJB methods, then all activity is covered by the same umbrella transaction.

If an EJB determines that the transaction should be rolled back, it can request a rollback on the current EJB SessionContext. The transaction isn’t actually rolled back until the final method returns. At that time, the EJB will throw a RollbackException.

There are six possible modes of transactional behavior:

  • REQUIRED : Create a new transaction or join the caller’s transaction.
  • REQUIRES_NEW : Create a new transaction. Suspend the caller’s transaction.
  • SUPPORTS : Supports transactions but does not require them. Joins the caller’s transaction, but doesn’t create new one if the caller is not transactional.
  • MANDATORY : Joins the caller’s transaction. Throws an exception if caller is not transactional.
  • NOT_SUPPORTED : Does not support transactions. Suspends caller’s transaction.
  • NEVER : Cannot run under any transaction. Throws an exception if caller is in a transaction.

EJB annotations

annotation target description
@Stateless class Indicates that a class is a stateless session bean.
@Stateful class Indicates that a class is a stateful session bean.
@MessageDriven class Indicates that a class is a message driven bean. Use @ActivationConfigProperty to indicate destination type (Queue or Topic) and the name of the destination name.
@Local interface Indicates that an interface is a local interface to an EJB.
@Remote interface Indicates that an interface is a remote interface to an EJB.
@PostConstruct method A method that needs to be executed after dependency injection is done to perform any initialization.
@PreDestroy method A callback notification to signal that the instance is in the process of being removed by the container.
@Remove method Indicates that the stateful session bean is to be removed by the container after completion of the method.
@PostActivate method A method to receive a callback after a stateful session bean has been activated.
@PrePassivate method A method to receive a callback before a stateful session bean is passivated.
@EJB variable Inject a reference to a named Enterprise JavaBean.
@Resource variable Inject a JNDI value.
@Interceptors class Declares AOP interceptors that will be called on a given EJB.
@AroundInvoke method Denotes AOP methods that will be called around EJB method calls.
@Timeout method Designates a method that will be called by the timer service.
@TransactionManagement class Declares the transaction management method: CONTAINER or BEAN.
@TransactionAttribute class Designates the container managed transaction type: MANDATORY, REQUIRED, REQUIRES_NEW, SUPPORTS, NOT_SUPPORTED, or NEVER.

EJB version 2 versus version 3

In J2EE, Enterprise JavaBeans were defined using a remote interface, an implementation, and a home interface. All class and interfaces needed to implement EJB-specific interfaces. All public methods must throw remote exceptions.

In EJB v3, all beans are POJOs; they need not implement any specific interfaces. Public methods do not need to throw remote exceptions. The home interfaces are not needed. You must still define a bean interface in v3 EJBs, but even this requirement is relaxed in v3.1.

Deployment of J2EE beans was defined by XML deployment descriptors. In EJB v3, deployment information can be put into Java annotations, although XML deployment descriptors may override the annotations.

In J2EE, persistence was provided by Entity beans. There were two types of persistence: Container Managed Persistence (CMP) where the application server automatically handled database interaction, and Bean Managed Persistence (BMP) where the bean implementation provided hand-coded JDBC persistence.

Persistence Strategies

Most persistence is ultimately based on JDBC code, but there many abstractions on top of this:

Inline JDBC code In this method, JDBC code is mixed in with other business logic. Mapping between Java objects and data is implicit in the SQL.
Since there isn’t much code reuse, this has poor ease of development, scalability, and extensibility. Security is based entirely on making database connections. Since it doesn’t reuse code that supports other security use cases, it doesn’t have great security characteristics. This method may be used for performance reasons, since you have complete control over the SQL, database hints, and database transaction management.
DAO A Data Access Object (DAO) abstracts and encapsulates all access to the persistent data. Again, mapping between Java and data is implicit in the code, but it is typical to create separate DAOs for each table.
This means that all the low-level JDBC code is pulled up into DAO classes. A DAO object represents an interface to a single table or to a whole domain model. Methods on the DAO may be low-level CRUD actions or higher-level business actions.
Since you’re still tweaking low-level JDBC code, this method still has difficult ease of development, meager security, but potentially good performance. This is some code re-use, so it has better qualities of extensibility and scalability.
Active Record The Active Record pattern also abstracts and encapsulates access to the persistent data.
In this pattern the domain classes are enhanced to include the low-level CRUD operations. We update or delete a database record by calling the update() or delete() method on the object.
Usage is similar to the DAO. Since the new functionality has a low level of abstraction, it is sometimes easier to use, but may require more work to do sophisticated business actions.
ORM Object Relational Mapping (ORM) allows programmers to deal in objects rather than SQL. Manipulation of persistent objects translates to create, read, update, and delete operations in the database. Mapping between objects and data is abstracted out, often to XML files or annotations or XDoclet comments.
This approach has significantly better ease of development, extensibility, and scalability compared with direct JDBC methods. Since the ORM library handles all database interactions, it may provide better portability between databases. The ORM system may integrate with application level security schemes, so security is at least as good as other methods. Database interaction may not be as optimal as hand-coded SQL, so performance may be sub-optimal.
JDO Java Data Objects is a standard for transparent object persistence. Mapping from objects to data is defined in XML files. The bytecode of Java classes are then enhanced so they execute CRUD operations as objects are manipulated.
Development characteristics are similar to ORM schemes. Ease of development may be improved by making persistence transparent, or decreased if it is more difficult to debug and test the enhanced classes.
JPA The Java Persistence API is a JEE standard ORM method. Mapping between Java objects and data are defined by annotations within the entity classes. The programming model is similar to Hibernate, and in fact version 3 of Hibernate resuses JPA’s annotations.
Development characteristics are similar to other ORM methods. Development is relatively easy. JPA provides portability between different application servers and databases. Security and transaction management integrates with other JEE technologies.
CMP Entity Beans J2EE Entity beans supported both Container Managed Persistence (CMP) and Bean Managed Persistence (BMP). With CMP, the mapping between objects and data was documented in XML files or using XDoclet. The EJB container handled database interaction similar to ORM schemes.
Early CMP implementations were criticized for having poor performance. Otherwise, characteristics are similar to JPA or other ORM schemes.
BMP Entity Beans With Bean Managed Persistence (BMP), all the persitence code was explicitely coded into the bean class.
This is similar to the DAO approach. It was labor intensive, but offered better performance. Security and transaction management worked with the application server and other J2EE technologies.

JPA annotations

annotation target description
@Entity class Indicates that a class is a persistable entity.
@Table class Specifies the database table for persisting an entity.
@Column field Specifies that column name for persisting a class variable
@Id field Specifies a primary key field in the table.
@Basic field Can be used to mark a field as optional and to indicate the fetch type (lazy or eager).
@Transient field Indicates that a field is not to be persisted.
@OneToOne field Field associates to another entity with one-to-one multiplicity.
@ManyToOne field Field associates one entity to a collection of other entities. Requires a @JoinColumn.
@OneToMany field Field associates a collection of entities to a single entity.
@ManyToMany field Field associates one entity to a collection of other entities and vice versa on the related entities. Requires a @JoinTable.
@PersistenceUnit variable Injects an EntityManagerFactory. The EntityManagerFactory is a thread-safe object.
@PersistenceContext variable Injects an EntityManager. Note that EntityManagers are not thread-safe.

Java EE Web Services

In J2EE, web services were created with JAX-RPC. In JAX-RPC, the service bean was called the Service Endpoint. Developers had to also define a Service Endpoint Interface (SEI) which extended java.rmi.Remote and where all public methods threw java.rmi.RemoteException.

In JEE 5, we use the JAX-WS API. In this new API, the SEI is optional and POJOs can be made into web services by annotations. When doing WSDL-first development, the SEI may be automatically generated during the build. The implementing class then becomes a simple POJO with minimal annotations.

JAX-WS supports SOAP 1.1 and SOAP 1.2. JAX-RPC supports only SOAP 1.1. JAX-WS supports WS-I Basic Profile 1.1, while JAX-RPC supports only Basic Profile 1.0. JAX-WS handles MTOM.

Any stateless session bean may be deployed as a SOAP web service. POJOs can be turned into web services by adding JAX-WS annotations to the class and method definitions.

SOAP web services have the advantage of being portable across different systems; Java can communicate to .Net or PHP or perl, etc. The interface definition is defined by a WSDL document, so communicating parties do not have to exchange class files.

Communicating XML over HTTP has some performance limitations. Both sides must serialize and deserialize XML. Communication tends to be stateless, so distributed transactions becomes difficult.

JAX-WS annotations

annotation target description
@WebService class Indicates that the class should be published as a web service.
@WebMethod method Indicates that a method is exposed as a web service operation.
@WebParam method
Customize WSDL aspects of an input parameter.
@WebResult method Customize WSDL aspects of an operation output.
@WebServiceRef variable Injects a reference to a web service client

Web service clients

JAX-RPC has a method for generating proxy clients at build-time. The resulting code may not be portable.

JAX-WS provides two ways of creating web service clients that are fully portable: dispatch clients and dynamic proxies.

A dispatch client allows manipulation of the XML in the whole soap message or just in the payload XML. A dispatch proxy dos not require the WSDL, schema, or SEI.

A dynamic proxy is dynamically generated at run-time using Java 5 dynamic proxies. With dynamic proxies a client causes a proxy to be created based on the SEI and (optionally) the WSDL. Methods called on the proxy cause methods to be called on the remote implementation.

The @WebServiceRef annotation can be used to mark an SEI as a JNDI resource, or for injecting a dynamic proxy into client code.

Alternative web service technologies

XML-RPC is an older, simpler protocol for making remote procedure calls by sending XML over HTTP. There is Java code for XML-RPC for servers and clients.

An entirely different web service architecture is Representational State Transfer (REST), where data is viewed as a collection of resources each referenced by a URI. In REST, data looks like HTML (although it is typically represented in XML or JSON) and data manipulation looks like HTTP (although it could be implemented with other protocols). A REST architecture is sometimes refered to as Web Oriented Architecture (WOA). Sun will support JAX-RS as an API for REST in future JEE standards.

%d bloggers like this: