Working with Binary Data using EJB

August 5, 2009 at 9:13 am (Programs) ()

// Working with Binary Data in EJB

File: CustomerType.java

public enum CustomerType
{
UNREGISTERED,
REGISTERED,
BIG_SPENDAH
}

File: Employee.java

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
//@Table(name=”EMP”, schema=”HR”)
@Table(name=“EMP”)
public class Employee implements Serializable {
@Id
@Column(name = “EMP_ID”)
private int id;
@Column(name = “COMM”)
private String name;
@Column(name = “SAL”)
private long salary;

private CustomerType customerType;
private Date timeCreated = new Date();
private MyImage picture;

public Employee() {
}

public Employee(int id) {
this.id = id;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public long getSalary() {
return salary;
}

public void setSalary(long salary) {
this.salary = salary;
}

@Enumerated(EnumType.STRING)
public CustomerType getCustomerType() { return customerType; }
public void setCustomerType(CustomerType type) { customerType = type; }

@Temporal(TemporalType.TIME)
public Date getTimeCreated() { return timeCreated; }
public void setTimeCreated(Date time) { timeCreated = time; }

@Lob @Basic(fetch=FetchType.LAZY)
public MyImage getPicture() { return picture; }
public void setPicture(MyImage jpeg) { picture = jpeg; }

public String toString() {
return “Employee id: ” + getId() + “ name: ” + getName() + “ salary: ” + getSalary();
}
}

File: EmployeeService.java

import java.util.Collection;

import javax.ejb.Remove;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class EmployeeService implements EmployeeServiceLocal, EmployeeServiceRemote {
@PersistenceContext(unitName=“EmployeeService”)
EntityManager em;

public EmployeeService() {
}

public Employee createEmployee(Employee emp) {
em.persist(emp);
em.flush();
return emp;
}
public Employee createEmployee(int id, String name, long salary) {
Employee emp = new Employee(id);
emp.setName(name);
emp.setSalary(salary);

em.persist(emp);
em.flush();
return emp;
}

public void removeEmployee(int id) {
Employee emp = findEmployee(id);
if (emp != null) {
em.remove(emp);
}
}

public Employee raiseEmployeeSalary(int id, long raise) {
Employee emp = em.find(Employee.class, id);
if (emp != null) {
emp.setSalary(emp.getSalary() + raise);
}
return emp;
}

public Employee findEmployee(int id) {
return em.find(Employee.class, id);
}

public Collection<Employee> findAllEmployees() {
Query query = em.createQuery(“SELECT e FROM Employee e”);
return (Collection<Employee>) query.getResultList();
}

public void doAction(){
}

@Remove
public void remove()
{
System.out.println(“removed”);
}
}

File: EmployeeServiceLocal.java

import java.util.Collection;

import javax.ejb.Local;

@Local
public interface EmployeeServiceLocal {
public void doAction();

public Employee createEmployee(int id, String name, long salary) ;
public Employee createEmployee(Employee emp) ;
public void removeEmployee(int id);
public Employee raiseEmployeeSalary(int id, long raise) ;
public Employee findEmployee(int id);
public Collection<Employee> findAllEmployees() ;
}

File: EmployeeServiceRemote.java

import java.util.Collection;

import javax.ejb.Remote;

@Remote
public interface EmployeeServiceRemote{
public void doAction();
public Employee createEmployee(int id, String name, long salary) ;
public Employee createEmployee(Employee emp) ;
public void removeEmployee(int id);
public Employee raiseEmployeeSalary(int id, long raise) ;
public Employee findEmployee(int id);
public Collection<Employee> findAllEmployees() ;

}

File: MyImage.java

public class MyImage implements java.io.Serializable
{
public MyImage() {}
}

File: Main.java

import java.util.Collection;

import javax.naming.InitialContext;

public class Main {

public static void main(String[] a) throws Exception {

EmployeeServiceRemote service = null;

// Context compEnv = (Context) new InitialContext().lookup(“java:comp/env”);

// service = (HelloService)new InitialContext().lookup(“java:comp/env/ejb/HelloService”);
service = (EmployeeServiceRemote) new InitialContext().lookup(“EmployeeService/remote”);



service.createEmployee(158, “AAA”, 45000);
service.createEmployee(159, “AAA”, 45000);

Employee emp = new Employee();
emp.setId(160);
emp.setCustomerType(CustomerType.BIG_SPENDAH);
MyImage oneUglyDude = new MyImage();
emp.setPicture(oneUglyDude);

service.createEmployee(emp);
Employee emp1 = service.findEmployee(160);
System.out.println(emp1);

Collection<Employee> list = service.findAllEmployees();

System.out.println(list);
}

}

File: jndi.properties

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost:1099

Permalink Leave a Comment

EJB – Two Marks Q & A

May 2, 2008 at 9:57 am (EJB, Technical Questions, Two Marks) (, )

What is EJB?

EJB stands for Enterprise Java Bean and is widely-adopted server side component architecture for J2EE. It enables rapid development of mission-critical application that are versatile, reusable and portable across middleware while protecting IT investment and preventing vendor lock-in.

What is the difference between EJB and Java beans?

EJB is a specification for J2EE server, not a product; Java beans may be a graphical component in IDE.

What is EJB role in J2EE?

EJB technology is the core of J2EE. It enables developers to write reusable and portable server-side business logic for the J2EE platform.

What are the key features of the EJB technology?

1. EJB components are server-side components written entirely in the Java programming language

2. EJB components contain business logic only – no system-level programming & services, such as transactions, security, life-cycle, threading, persistence, etc. are automatically managed for the EJB component by the EJB server.

3. EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and secure.

4. EJB components are fully portable across any EJB server and any OS.

5. EJB architecture is wire-protocol neutral–any protocol can be utilized like IIOP,JRMP, HTTP, DCOM,etc.

What are the key benefits of the EJB technology?

1. Rapid application development

2. Broad industry adoption

3. Application portability

4. Protection of IT investment

How many enterprise beans?

There are three kinds of enterprise beans:

1. session beans,

2. entity beans, and

3. Message-driven beans.

What is message-driven bean?

A message-driven bean combines features of a session bean and a Java Message Service (JMS) message listener, allowing a business component to receive JMS. A message-driven bean enables asynchronous clients to access the business logic in the EJB tier.

What are Entity Bean and Session Bean?

Entity Bean is a Java class which implements an Enterprise Bean interface and provides the implementation of the business methods. There are two types: Container Managed Persistence (CMP) and Bean-Managed Persistence (BMP).

Session Bean is used to represent a workflow on behalf of a client. There are two types: Stateless and Stateful. Stateless bean is the simplest bean. It doesn’t maintain any conversational state with clients between method invocations. Stateful bean maintains state between invocations.

What is Session Bean? Explain

A session bean is a non-persistent object that implements some business logic running on the server. One way to think of a session object is as a logical extension of the client program that runs on the server.


Session beans are used to manage the interactions of entity and other session beans,access resources, and generally perform tasks on behalf of the client.


There are two basic kinds of session bean: stateless and stateful.


Stateless session beans are made up of business methods that behave like procedures; they operate only on the arguments passed to them when they are invoked. Stateless beans are called stateless because they are transient; they do not maintain business state between method invocations. Each invocation of a stateless business method is independent from previous invocations. Because stateless session beans are stateless, they are easier for the EJB container to manage, so they tend to process requests faster and use fewer resources.


Stateful session beans encapsulate business logic and state specific to a client. Stateful beans are called “stateful” because they do maintain business state between method invocations, held in memory and not persistent. Unlike stateless session beans, clients do not share stateful beans. When a client creates a stateful bean, that bean instance is dedicated to service only that client. This makes it possible to maintain conversational state, which is business state that can be shared by methods in the same stateful bean.

What is the difference between session and entity beans?

An entity bean represents persistent global data from the database; a session bean represents transient user-specific data that will die when the user disconnects (ends his session). Generally, the session beans implement business methods (e.g. Bank.transferFunds) that call entity beans (e.g. Account.deposit, Account.withdraw)

What are the services provided by container?

Container services are totally depends upon the “vendor implementation”. But more or less most of the vendors suppots the basic services like,

1. LifeCycle Management – It is Automatic.

2. Session Management – it is used by Developer coded callback methods…

3. Transaction Management – it is used by configuring deployment descriptor (DD).

4. Security management – it is used by configuring deployment descriptor (DD).

The other services, if any will be in advanced versions, and depends on Vendor specific.

What is Deployment descriptor?

A deployment descriptor is an XML file packaged with the enterprise beans in an EJB JAR file or an EAR file. It contains metadata describing the contents and structure of the enterprise beans, and runtime transaction and security information for the EJB container.

How many EJB Objects are created for a Bean?

For a Session bean – one EJB object for one bean instance.

For entity bean – it depends , if two users are accessing one row at time then one EJB object is used for both the beans other wise for each bean one EJB object.

What is re-entrant. Is session beans reentrant. Is entity beans reentrant?
If we define the entity bean as being reentrant, multiple clients can connect to the Entity bean & execute methods within the entity bean concurrently. Container takes care of synchronization. If we define the entity bean as non-reentrant and many clients connect to it concurrently to execute a method, exception is thrown

What is EJB container?

An EJB container is a run-time environment that manages one or more enterprise beans. The EJB container manages the life cycles of enterprise bean objects, coordinates distributed transactions, and implements object security. Generally, each EJB container is provided by an EJB server and contains a set of enterprise beans that run on the server.

What is EJB server?

An EJB server is a high-level process or application that provides a run-time environment to support the execution of server applications that use enterprise beans. An EJB server provides a JNDI-accessible naming service, manages and coordinates the allocation of resources to client applications, provides access to system resources, and provides a transaction service. An EJB server could be provided by, for example, a database or application server.

What is the difference between ejbCreate() and ejbPostCreate?

The purpose of ejbPostCreate() is to perform clean-up database operations after SQL INSERTs (which occur when ejbCreate() is called) when working with CMP entity beans. ejbCreate() is called before database INSERT operations. You need to use ejbPostCreate() to define operations, like set a flag, after INSERT completes successfully.

Why does EJB needs two interfaces(Home and Remote Interface)

There is a pure division of roles between the two .
Home Interface is the way to communicate with the container which is responsible for creating , locating and removing beans and Remote Interface is the link to the bean that allows acces to all methods and members.

What is the difference between a Server, a Container, and a Connector?

An EJB server is an application, usually a product such as BEA WebLogic, that provides (or should provide) for concurrent client connections and manages system resources such as threads, processes, memory, database connections, network connections, etc. An EJB container runs inside (or within) an EJB server, and provides deployed EJB beans with transaction and security management, etc. The EJB container insulates an EJB bean from the specifics of an underlying EJB server by providing a simple, standard API between the EJB bean and its container. A Connector provides the ability for any Enterprise Information System (EIS) to plug into any EJB server which supports the Connector architecture. See Sun’s J2EE Connectors for more in-depth information on Connectors.

Why is ejbFindByPrimaryKey mandatory?

An Entity Bean represents persistent data that is stored outside of the EJB Container/Server. The ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the container, similar to a SELECT statement in SQL. By making this method mandatory, the client programmer can be assured that if they have the primary key of the Entity Bean, then they can retrieve the bean without having to create a new bean each time – which would mean creating duplications of persistent data and break the integrity of EJB.

What is the default transaction attribute for an EJB?

There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec says that the deployer must specify a value for the transaction attribute for those methods having container managed transaction. In WebLogic, the default transaction attribute for EJB is SUPPORTS.

What is software architecture of EJB?

Session and Entity EJBs consist of 4 and 5 parts respetively:

1. A remote interface (a client interacts with it),

2. A home interface (used for creating objects and for declaring business methods),

3. A bean object (an object, which actually performs business logic and EJB-specific operations).

4. A deployment descriptor (an XML file containing all information required for maintaining the EJB) or a set of deployment descriptors (if you are using some container-specific features).

5. A Primary Key class – is only Entity bean specific.

What is an EJB Context?

EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions.

Permalink Leave a Comment

EJB – Interview Questions & Answers

May 2, 2008 at 9:54 am (EJB, Technical Questions) (, )

What is session Facade?

Session Facade is a design pattern to access the Entity bean through local interface than accessing directly. It increases the performance over the network. In this case we call session bean which on turn call entity bean.

What technologies are included in J2EE?

The main technologies in J2EE are: Enterprise JavaBeansTM (EJBsTM), JavaServer PagesTM (JSPsTM), Java Servlets, the Java Naming and Directory InterfaceTM (JNDITM), the Java Transaction API (JTA), CORBA, and the JDBCTM data access API.

What is EJB role in J2EE?

EJB technology is the core of J2EE. It enables developers to write reusable and portable server-side business logic for the J2EE platform.

What is Enterprise JavaBeans (EJB) container?

It manages the execution of enterprise beans for J2EE applications.
Enterprise beans and their container run on the J2EE server.

What is the new basic requirement for a CMP entity bean class in 2.0 from that of ejb 1.1?

It must be abstract class. The container extends it and implements methods which are required for managing the relationships

What’s new in the EJB 2.0 specification?

Following are some of the main features supported in EJB 2.0:

1. Integration of EJB with JMS,

2. Message Driven Beans,

3. Implement additional Business methods in Home interface which are not specific for bean instance, EJB QL.

How can I access EJB from ASP?

We can use the Java 2 Platform, Enterprise Edition Client Access Services (J2EETM CAS) COM Bridge 1.0, currently downloadable from Sun

How EJB Invocation happens?

Step 1: Retrieve Home Object reference from Naming Service via JNDI.

step 2: Return Home Object reference to the client.

step 3: Create me a new EJB Object through Home Object interface.

step 4: Create EJB Object from the Ejb Object

step 5: Return EJB Object reference to the client.

step 6: Invoke business method using EJB Object reference.

step 7: Delegate request to Bean (Enterprise Bean).

What is the relationship between local interfaces and container-managed relationships?
Entity beans that have container-managed relationships with other entity beans, must be accessed in the same local scope as those related beans, and therefore typically provide a local client view. In order to be the target of a container-managed relationship, an entity bean with container-managed persistence must provide a local interface.

Are enterprise beans allowed to use Thread.sleep()?

Enterprise beans make use of the services provided by the EJB container, such as life-cycle management. To avoid conflicts with these services, enterprise beans are restricted from performing certain operations: Managing or synchronizing threads

What are Local Interfaces? Describe.

EJB was originally designed around remote invocation using the Java Remote Method Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without consideration for the deployment scenario, and was a strong feature in support of a goal of component reuse in J2EE. Many developers are using EJBs locally, that is, some or all of their EJB calls are between beans in a single container. With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which co-location is planned. Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence.

What are transaction isolation levels in EJB?

1. Transaction_read_uncommitted- Allows a method to read uncommitted data from a DB(fast but not wise).

2. Transaction_read_committed- Guarantees that the data you are getting has been committed.

3. Transaction_repeatable_read – Guarantees that all reads of the database will be the same during the transaction (good for read and update operations).

4. Transaction_serializable- All the transactions for resource are performed serial.

What is the difference between Container-Managed Persistent (CMP) bean and Bean-Managed Persistent(BMP) ?

Container-managed persistence beans are the simplest for the bean developer to create and the most difficult for the EJB server to support. This is because all the logic for synchronizing the bean’s state with the database is handled automatically by the container. This means that the bean developer doesn’t need to write any data access logic, while the EJB server is supposed to take care of all the persistence needs automatically. With CMP, the container manages the persistence of the entity bean. A CMP bean developer doesn’t need to worry about JDBC code and transactions, because the Container performs database calls and transaction management instead of the programmer. Vendor tools are used to map the entity fields to the database and absolutely no database access code is written in the bean class. All table mapping is specified in the deployment descriptor. Otherwise, a BMP bean developer takes the load of linking an application and a database on his shoulders.


The bean-managed persistence (BMP) enterprise bean manages synchronizing its state with the database as directed by the container. The bean uses a database API to read and write its fields to the database, but the container tells it when to do each synchronization operation and manages the transactions for the bean automatically. Bean-managed persistence gives the bean developer the flexibility to perform persistence operations that are too complicated for the container or to use a data source that is not supported by the container.BMP beans are not 100% database-independent, because they may contain database-specific code, but CMP beans are unable to perform complicated DML (data manipulation language) statements. EJB 2.0 specification introduced some new ways of querying database (by using the EJB QL – query language).

What is bean managed transaction?

If a developer doesn’t want a Container to manage transactions, it’s possible to implement all database operations manually by writing the appropriate JDBC code. This often leads to productivity increase, but it makes an Entity Bean incompatible with some databases and it enlarges the amount of code to be written. All transaction management is explicitly performed by a developer.

What are transaction attributes?

The transaction attribute specifies how the Container must manage transactions for a method when a client invokes the method via the enterprise bean’s home or component interface or when the method is invoked as the result of the arrival of a JMS message. (Sun’s EJB Specification) Below is a list of transactional attributes:

1. NotSupported – transaction context is unspecified.

2. Required – bean’s method invocation is made within a transactional context. If a client is not associated with a transaction, a new transaction is invoked automatically.

3. Supports – if a transactional context exists, a Container acts like the transaction attribute is Required, else – like NotSupported.

4. RequiresNew – a method is invoked in a new transaction context.

5. Mandatory – if a transactional context exists, a Container acts like the transaction attribute is Required, else it throws a javax.ejb.TransactionRequiredException.

6. Never – a method executes only if no transaction context is specified.

What is the difference between Message Driven Beans and Stateless Session beans?

In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways: Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls. Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic. Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary. The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls.


Permalink 1 Comment

What is the difference between find and select methods in EJB?

May 2, 2008 at 9:32 am (EJB, Technical Questions) (, )

A select method can return a persistent field (or a collection thereof) of a related entity bean. A finder method can return only a local or remote interface (or a collection of interfaces).

Because it is not exposed in any of the local or remote interfaces, a select method cannot be invoked by a client. It can be invoked only by the methods implemented within the entity bean class. A select method is usually invoked by either a business or a home method.

A select method is defined in the entity bean class. For bean-managed persistence, a finder method is defined in the entity bean class, but for container-managed persistence it is not.

Permalink Leave a Comment

What are the methods of Entity Bean? Explain

May 2, 2008 at 9:30 am (EJB, Technical Questions) (, )

An entity bean consists of 4 groups of methods:

1. create methods: To create a new instance of a CMP entity bean, and therefore insert data into the database, the create() method on the bean’s home interface must be invoked. They look like this: EntityBeanClass ejbCreateXXX(parameters), where EntityBeanClass is an Entity Bean you are trying to instantiate, ejbCreateXXX(parameters) methods are used for creating Entity Bean instances according to the parameters specified and to some programmer-defined conditions.


A bean’s home interface may declare zero or more create() methods, each of which must have corresponding ejbCreate() and ejbPostCreate() methods in the bean class. These creation methods are linked at run time, so that when a create() method is invoked on the home interface, the container delegates the invocation to the corresponding ejbCreate() and ejbPostCreate() methods on the bean class.


2. finder methods: The methods in the home interface that begin with “find” are called the find methods. These are used to query the EJB server for specific entity beans, based on the name of the method and arguments passed. Unfortunately, there is no standard query language defined for find methods, so each vendor will implement the find method differently. In CMP entity beans, the find methods are not implemented with matching methods in the bean class; containers implement them when the bean is deployed in a vendor specific manner. The deployer will use vendor specific tools to tell the container how a particular find method should behave. Some vendors will use object-relational mapping tools to define the behavior of a find method while others will simply require the deployer to enter the appropriate SQL command.


There are two basic kinds of find methods: single-entity and multi-entity. Single-entity find methods return a remote reference to the one specific entity bean that matches the find request. If no entity beans are found, the method throws an ObjectNotFoundException . Every entity bean must define the single-entity find method with the method name findByPrimaryKey(), which takes the bean’s primary key type as an argument.


The multi-entity find methods return a collection ( Enumeration or Collection type) of entities that match the find request. If no entities are found, the multi-entity find returns an empty collection.


3. remove methods: These methods (you may have up to 2 remove methods, or don’t have them at all) allow the client to physically remove Entity beans by specifying either Handle or a Primary Key for the Entity Bean.


4. home methods:
These methods are designed and implemented by a developer, and EJB specification doesn’t have any requirements for them except the need to throw a RemoteException is each home method

Permalink Leave a Comment

What is EJB architecture(components)?

May 2, 2008 at 9:08 am (EJB, Technical Questions) (, )

Enterprise beans-An enterprise bean is a non-visual component of a distributed, transaction-oriented enterprise application. Enterprise beans are typically deployed in EJB containers and run on EJB servers.


There are three types of enterprise beans: session beans, entity beans, and message-driven beans.

Session beans: Session beans are non-persistent enterprise beans. They can be stateful or stateless. A stateful session bean acts on behalf of a single client and maintains client-specific session information (called conversational state) across multiple method calls and transactions. It exists for the duration of a single client/server session. A stateless session bean, by comparison, does not maintain any conversational state. Stateless session beans are pooled by their container to handle multiple requests from multiple clients.

Entity beans: Entity beans are enterprise beans that contain persistent data and that can be saved in various persistent data stores. Each entity bean carries its own identity. Entity beans that manage their own persistence are called bean-managed persistence (BMP) entity beans. Entity beans that delegate their persistence to their EJB container are called container-managed persistence (CMP) entity beans.

Message-driven beans: Message-driven beans are enterprise beans that receive and process JMS messages. Unlike session or entity beans, message-driven beans have no interfaces. They can be accessed only through messaging and they do not maintain any conversational state. Message-driven beans allow asynchronous communication between the queue and the listener, and provide separation between message processing and business logic.

Permalink Leave a Comment

Persistence Problems

April 30, 2008 at 12:52 pm (EJB, Extra) ()

By Geir Magnusson Jr. and Jeremy Boynes

June 9, 2004

By Geir Magnusson and Jeremy Boynes

We seem to have a big problem in the Java persistence community, and it’s one that seems to have a surprisingly simple solution.

Storm clouds

About mid-May 2004, we began to suspect that things weren’t quite right, about the time the SE/EE Executive Committee voted on JSR-243 for JDO 2.0. Several EC members voted against the JSR, although it did pass. You can read about it here. [Full Disclosure from Geir : I'm the Apache EC rep and voted yes because I think that despite assertions to the contrary, there is no overlap with existing technology, and if there *is* overlap, competition is good - let the market decide.] Looking back, there was a hint of storm clouds on the horizon with Oracle’s comment, namely that JDO 2.0 overlaps work being done in the EJB expert group. We didn’t think anything of it at the time (“JDBC overlaps work being done in the JNDI expert group” if you believe that both are ways of retrieving data) but with the benefit of hindsight, it’s almost as if Oracle was warning us about what was coming.

Looking back at the comments, we also have several references to J2EE. JDO isn’t part of the J2EE spec – JSR-243 notes it will work to be more “aligned” with J2EE – and J2EE isn’t the only platform under which people build applications. JDO is important for non-J2EE developers working on J2SE applications. With further hindsight, we see from those comments that several platform vendors appear to have identified a developer need unfilled in the J2EE platform.

The Three Tiers of the Persistence Inquisition

We tend to think about persistence tools in the way we think about any other set of developer tools for a given technology. Generally, once software engineers have enough experience in a problem domain, they will produce a set of development techniques or models which are designed to address different levels of complexity in that problem domain. They tend to build on one another and if lucky, there’s a reasonable path for moving ‘up the chain’ as an application’s complexity increases. This model and tool approach is true with persistence as well:

  1. Simple and Uncomplicated: At the bottom of the complexity stack of Java data persistence is the old ‘fast and dirty’ standby that we all know and don’t truly love – JDBC. We’ve all used it and gotten quite a bit done with it, but it’s not terribly pleasant when we live in an object-oriented world (or even a data-structure world). We tend to write simple tools to help us around the “bare metal”, and after a while, we stand back, look at those simple tools, and and decide that we need a better level of abstraction to handle the domain model that we work in. That leads to tools and models of medium complexity.
  2. Medium complexity: This consists of tools that allow us to work easier with the everyday objects and data structures that make up our applications. This isn’t a new idea, and probably extends from seeing object database systems and, not being able to actually find any in the market ;) , wanting to use general purpose RDBM systems for the same purpose. There is a wide range of approaches to this problem, from populating JavaBeans from XML (and back) to POJO persistence, with solutions ranging from standard to proprietary, commercial to open-source. Examples include the Java JDO specification with it’s implementations, commercial proprietary O/R systems like TopLink and the current crop of open-source solutions like Hibernate, OJB, Cheyanne, et al. The basic idea in middle-complexity-land is fundamentally about persisting POJOs (Plain Old Java Objects). These approaches generally are very convenient to use, allow you to work without any component contracts forced on your classes by the environment, and more or less give you the freedom to easily save objects or graphs of objects to some kind of data store and get them back later. They tend to be “deliberate” – the programmer makes the decision about when to save with some kind of explicit POJOFramework.save(myObject) call or -ish. They also are very popular (and becoming increasingly so) because most applications seem to be at this level of complexity – you just want to work with your domain objects in a deliberate way. (Or even just use to ‘persisted data structures’, which is my favorite use for Hibernate, for example).
  3. High Complexity: To address high levels of complexity, we have complicated frameworks like EJB that provide middleware services such as transactions, security, data storage, component relationship management, etc. This third tier is generally very powerful, very complicated, and seems to be often misapplied. Because it’s part of the ‘enterprise’ Java standard, it’s the ‘natural’ choice for persisting data in an ‘enterprise’ application, although there are other solutions that, depending on the application, would be just as appropriate and easier for the developer to use, deploy and maintain – solutions from medium-complexity-land that aren’t part of the J2EE spec.

J2EE, EJB and Thee

With the preceding discussion in mind, lets look at what’s been happening with the next version of J2EE. According to the text of JSR-244, the theme of J2EE 1.5 is “ease of development”, with the goal of addressing the needs of a wide range of developers, “including less sophisticated developers”. This is a laudable goal, and quite frankly, it’s about time. By adding new features that enable better tool support, ease of application development, and ease of maintenance, the Java will hopefully become more widely adopted and remain a competitive platform for enterprise development.

Expert groups that are part of the J2EE “umbrella” are working to support that goal, and this includes Enterprise Java Beans (EJB). The JSR for EJB 3, JSR-220, has the following as its declared purpose :

“The Enterprise JavaBeans architecture is a component architecture for the development and deployment of component-based business applications. The purpose of Enterprise JavaBeans (EJB) 3.0 is to improve the EJB architecture by reducing its complexity from the developer’s point of view.”

It makes it pretty clear that EJB is a component architecture (and happens to include the ‘high complexity tier’ of data persistence) and the intent of this version is to improve the architecture by reducing complexity. This is just fabulous.

POJO Persistence and Mission Creep

As we’ve heard at TheServerSide Symposium and other places, the EJB expert group is working on what amounts to splitting the EJB spec into two concurrent ‘tracks’. They don’t talk about it like this, but it’s a reasonable interpretation :

  • an addition of a new and incompatible POJO persistence model
  • a continuation of the EJB 2 component architecture with new POJO persistence model features backported (changes to query language, for instance)

We think that one conclusion that we can safely draw from this is that the EJB3 expert group recognizes that EJB2 persistence doesn’t satisfy the needs of a large number, if not the majority, of enterprise application developers. Further, they recognize that POJO persistence is a valid persistence strategy and developers like to use it for their applications. They are so interested in having it available, the EJB expert group is willing to alter the objective of the JSR to accommodate.

I think that we should appreciate the EJB3 EG for the courageous step of effectively saying “We realize there’s more to enterprise data persistence than EJBs and we want to do something about it” It’s not unreasonable, though, to presume that this ‘bifurcation’ of the EJB spec will be fairly confusing for developers because now EJBs are going to be “EJBv2 EJBs” and “persisted POJO EJBs”.

Paying attention to customer demand is laudable, but when you consider that these two technologies (POJO persistence and EJBs) are arguably two distinct solutions to data persistence appropriate for differing levels of application complexity (and EJB is more than just data persistence), this bifurcation of the spec begs a question :

“Could we prevent an over-broad and potentially confusing EJB model by simply adding POJO persistence separately to the J2EE spec for 1.5?”

One would assume, given the investment made by users and vendors of J2EE, that an incremental revision of the J2EE spec (from 1.4 to 1.5) would presume a compatibility path that preserves existing investment and allows those implementations to smoothly take advantage of new features. Users aren’t going to want to rewrite critical business applications just to keep up with vendors. What we seem to be seeing here is a discontinuous change from EJB2 to EJB3 and there is no smooth path from EJB2 applications to EJB3 applications.

To answer the question above, we could achieve the same result by making a POJO persistence model available in J2EE distinct from EJB without compromising EJBs, which are a valuable and appropriate solution for a small percentage of highly-complex enterprise applications. Not everyone needs EJB, but when you do, you do!

The obvious solution – “Well, you’ve had a JSR for POJO persistence for some years now… JDO – why not add it to J2EE?” – is an answer that no one seems to want to hear because there appears to be a war going on between the JDO and EJB communities. Technology battles aren’t new, but this one is astounding in it’s irony. The EJB3 group, by adding POJO persistence, is validating the whole argument for JDO or a JDO-like technology in J2EE. There will be arguments about technical details such as choice of query language, approaches to detaching object graphs, etc but at the end of the day, the EJB EG is advocating the addition of a technology approach that already exists in the “Java ecosystem” – JDO – into J2EE.

We’re optimistic that this can be resolved. We don’t believe that a spec lead can be held responsible for the public behavior of the expert group members or non-EG members of the community. However, as both specs are Sun sponsored, both spec leads are Sun employees and most importantly, all parties agree on the fundamental need for POJO persistence in J2EE, it’s conceivable that through a concerted effort by Sun to recognize the gap in J2EE and work towards an architecturally clean solution, partisans from both sides can work with each other rather than against each other.

Solution!

The simplest solution is to add POJO persistence (via JDO 2.0 or other) to the J2EE umbrella. As a bonus, require that POJO persistence and EJB work from the same persistence layer, so that concurrently deployed applications written using both technologies have coherent views of the same data. (And if vendors are smart, they’ll provide a JDBC driver to access the same persistence layer….)

While fixing J2EE to support what programmers want today, it also offers a compelling path to J2EE from J2SE, because J2SE applications that are written using the same POJO persistence model will be able to migrate to the J2EE environment without requiring changes to their persistence model. Further, we can take a lesson from Microsoft’s ADO and tools such as Hibernate and OJB in Java – that there is a strong demand for persistent objects in the base platform. So lets also ensure that we take what we learn from J2EE 1.5 and push what we can ‘down’ to J2SE 1.6. (On that note, how many people know about the rejected JSR-20?)

JDO 2.0 just got started. Any of the supposed deficiencies in JDO can be addressed. If, in the opinion of the J2EE EG, that JDO’s model is inappropriate – that recent work in open-source or commercial solutions offer compelling alternatives – start a new EG and include members from JDO as well as EJB.

We feel that this is an important problem, but a very manageable one, and hope that the broad Java community supports this approach – addressing the needs of the development community is one of the core purposes of the JCP. Lets use it.

Note: The above represents the personal opinion of Geir and Jeremy and should be not construed to represent the position of any other organization. Specifically, this does not represent the position of the Apache Software Foundation.

Full Disclosure: Geir is the Apache representative to the JCP Executive Committee and recently the current Apache representative on the J2EE 1.5 Expert Group. Jeremy is the Apache representative on the EJB3 expert group. This article is an original work by Geir and Jeremy based on public information and should not be construed to represent either EC or EG confidential information, future intention or past or current discussion. If any of this has been discussed in an EG, it is without our knowledge and we consider ourselves lucky.

Permalink Leave a Comment

Simplifying EJB Development with EJB 3.0

April 30, 2008 at 12:49 pm (EJB, Extra) ()

By Debu Panda


October 2004

Discussion

Enterprise JavaBeans (EJB) was introduced for building distributed components. When it arrived it came with a promise to solve all issues and complexities of CORBA. EJB being the heart of J2EE went through several major revisions and got fattened with many features. Early on, most of the developers fell in love with EJB and used EJB in their application even it did not make any sense. “Blame it on EJB” has been the attitude for many developers when their projects did not scale well and they used EJB.

Development of EJB was never easier and it became more complex with every release of EJB specification. EJB has been compared with an elephant due to its complexity and heavy weight nature. Many developers feel EJB is like an extra layer of sugar syrup on a doughnut. In an age where low carb and Atkins diet is craze, the EJB expert committee has no option but to produce a low carb incarnation of EJB thus simplifying the development of EJB. EJB 3.0 expert committee released a sample picture of the lightweight model during JavaOne 2004 when it announced release of first public draft of EJB 3.0 Specification.

At the first glimpse the new model for EJB looks pretty and in this article we will discuss how EJB 3.0 is trying to dress up in a smaller size pretty outfit to make it appealing for developers. In a follow up article we will discuss how EJB 3.0 is simplifying the persistence model.

Cleaning up the Dirty Laundry

Let us look at the complexities in the current EJB model before we dive down discussing the details what EJB 3.0 is bringing on to the table.

  • The current EJB model requires creation of several component interfaces and implementation of several unnecessary callback methods.
  • The component interfaces require implementation of EJBObject or EJBLocalObject and handling of many unnecessary exceptions is required.
  • The EJB deployment descriptor is complex and error prone.
  • The container managed persistence being based on the EJB model is again overly complex to develop and manage. There are several basic features missing such as a standard way to define a primary key using database sequence and EJBQL is very limited.
  • EJB components do not look like its Object Oriented as it has restrictions for using inheritance and polymorphisms.
  • One major drawback of EJBs is that you cannot test EJB modules outside an EJB container and debugging an EJB inside the container is a nightmare for developers.
  • If you used EJB you know the complexities of looking up and invocation of EJB. It appears that you have to know minute details of JNDI to just use an EJB in your application.

Simplifying Developers view

If you developed an EJB with the latest specification you realize how difficult is develop a simple EJB like HelloWorld EJB. You need at least two interfaces, a bean class and a deployment descriptor. Most of the developers wondered why do I need all these. IDEs like Oracle JDeveloper, Eclipse and XDoclet made the life simple for developers for doing these mundane tasks however still it was the responsibility of developer to compile these classes and package the deployment descriptor before the EJB can be deployed in your container of choice.

EJB 3.0 is trying to address the complexities by:

  • Removing need of interfaces and deployment descriptors and these may be generated by the container using metadata annotations
  • Use regular Java classes as EJBs and regular business interfaces for EJBs

Metadata Annotations

EJB 3.0 depends heavily on metadata annotations. Metadata annotation being standardized under JSR 175 and will be part of J2SE 5.0. Annotation is a kind of attribute oriented programming and similar to XDoclet. However unlike XDoclet that requires pre-compilation, annotations are compiled into the classes (depending upon what the @Retention is set to) by the Java compiler at compile-time. In developer’s point of view, annotations are modifiers like public and can be used in classes, fields, methods, parameters, local variables, constructors, enumerations and packages.You can use annotations in your Java code by specifying attributes that can be used for either generating code, documenting code or providing special services such as enhanced business-level security or special business logic during runtime. The goal of J2EE 1.5 (5.0) is to simplify development using annotations and hence it will come up with its set of annotations. Annotations are marked with @ as follows:

@Author(“Debu Panda”)

@Bean

public class MySessionBean

The goal of EJB 3.0 is to simplify development and hence use metadata annotations to generate several artifacts like interfaces and use annotations instead of deployment descriptors.

Using POJOs and POJIs

In canonical terms, JavaBeans and interfaces often referred as Plain Old Java Objects (POJOs) and Plain Old Java Interfaces (POJIs) respectively. The EJB class and interface will now resemble POJO and POJI respectively. The requirement of the unnecessary artifacts like home interface is being removed.

The developer has to either implement one of the EJB interfaces (SessionBean, EntityBean or MessageDrivenBean) in javax.ejb package or use annotation in the bean implementation class. You can either use Stateless, Stateful, MessageDriven or Entity to annotate your bean class. For example, if you define a stateless EJB as HelloWorld you define the EJB as follows:

@Remote

@Stateless public class HelloWorldBean {

public String sayHello(String s)

{ System.out.println(“Hello: “+s; }

}

The interfaces for EJBs either remote or local do not have to implement EJBObject or EJBLocalObject. You have to either supply the business interface for your EJB and implement that interface in your bean class or have it generated during the deployment. Interfaces are optional for Entity beans however required for SessionBean and MessageDrivenDriven. If you do not implement an interface for your session bean, a bean interface will be generated for you. The type of generated interface either local or remote is dependent on the annotation you used in the bean class. If you look at the above code example, it is very clear that @Remote is used to generate a remote interface for the HelloWorld bean. If needed, you may have both remote and local interfaces for your EJB.

From the above example, it is very clear that the developer do not have to a lot of mundane tasks such as defining interfaces and implementing callback methods.

The name of the generated interface is derived from the name of the bean implementation class. Generated interfaces are well and good for developers. However, I do not see any benefit of generating interfaces as most IDE like Oracle JDeveloper generates these on fly.

This is not clear from the draft what is client side requirement for EJB lookup and it is not clear, how do we get hold of these interfaces those are required to invoke this EJB? I will recommend against using a generated interface for few reasons:

  • The name of generated interface will be derived from the bean name
  • You may not be willing to expose some methods in the EJB in the interface and the generated interface may expose all methods by default.
  • You need the interface at the client side to invoke the EJB.

Removing need for Callback methods

EJB 2.1 and prior releases required implementation of several lifecycle methods such as ejbPassivate, ejbActivate, ejbLoad, ejbStore, etc. for every EJB even if you do not need those. For example, ejbPassivate is not required for a stateless session bean still you require to implement that method in your bean class. As EJB 3.0 now resembles regular Java classes implementation of these lifecycle methods have been made optional. If you implement any callback method in the EJB then container will invoke that method.

The only exception is the ejbRemove method in Stateful Session bean where you can use Remove annotation to annotate a Stateful session bean business method. If you use of this annotation it will hint the container to remove the Stateful session bean instance after the completion (normal or abnormal) of the annotated method. For example, you can specify the following to remove a Stateful Session Bean instance after checkOut method is executed.

@Stateful public class Cart {

@Remove public void checkOut() {

}

}

Annotations vs. deployment descriptors

As we discussed earlier deployment descriptors will no longer be required for EJBs and annotations will be used instead. The default values for each attribute in the deployment descriptor will be chosen and developers do not have to specify these attributes unless they want a value other than the default value. These can be specified using annotations in the bean class itself. The EJB 3.0 specification is defining a set of metadata annotations for use by developers such as bean type, type of interfaces, resource references, transaction attributes, security, etc. For example, if we want to resource reference for a particular EJB then we will define as follows:

@Resource(name=”jdbc/OracleDS”, resourceType=”javax.sql.DataSource”)

J2EE vendors such as Oracle, BEA, IBM will add annotations for attributes in their vendor specific deployment descriptors and developers will use these to avoid using deployment descriptors. This looks very attractive for developers as the nasty XML descriptors they hated most gets out of their way but this introduces few problems and we need to be careful before embracing annotations.

  • This defeats the goal of portability of applications because if an EJB uses a vendor specific deployment descriptor this cannot be just changed without having to recompiling/repackaging the EJBs.
  • The deployment descriptors provided a holistic view of EJB modules to the assembler/deployer (ejb-jar) without having to look at individual the EJBs and they tweaked these as per the deployment requirement and if descriptors are not available or not generated until the end of deployment this could be a nightmare for them.
  • Deployment descriptors were used by the tools to identify the EJBs in an EJB module and were very useful when you try to migrate from one container to another.
    EJB 3.0 spec also proposes a way to override the annotations in the deployment descriptors. However details of overriding annotations is missing in the specification.

There is no doubt that getting rid of deployment descriptors will make the life easier for new developers but this may become a management nightmare if not used carefully.

Simplifying Container Managed Persistence

CMP entity bean is getting a major overhaul in EJB 3.0 to make it compelling for developers. Persistence frameworks like OracleAS TopLink, open source Hibernate have become darling of developing persistence framework for J2EE applications that has disliked Entity beans for its complexity and heavyweight in nature. EJB 3.0 is adopting a lightweight persistence model like TopLink and Hibernate to simplify the container managed persistence and this sounds compelling for developers. Let us do a quick look on the plans for entity beans and we will discuss about the details of the persistence improvement in another article.

Entity beans are being reincarnated as POJOs and there will be no component interfaces required for entity beans. Entity beans will now look as pure objects as this will also support inheritance and polymorphism.

Following is the source code for an entity bean:

@Entity public class Employee{

private Long empNo;

private String empName;

private Address address;

private Hashmap projects = new Hashmap();

private Double salary;

@Id(generate=SEQUENCE) public Long getEmpNo() {

return empNo;

}

protected void setEmpNo(Long empNo) {

this.empNo = empNo;

}

public String getEmpName() {

return EmpName;

}

public void setEmpName(String EmpName){

this.EmpName = EmpName;

}

@Dependent public Address getAddress() {

return address;

}

public void setAddress(Address address) {

this.address = address;

}

public Set getProjects() {

return projects;

}

public void setProjects(Set projects) {

this.projects = projects;

}

public Double getSalary() {

return salary;

}

public void setSalary(Double salary) {

this.salary = salary;

}

….

}

If you look at the code, you will find that the bean class is a concrete class and not an abstract class the current entity bean.

There are several improvements are being made for the query capabilities in EJB QL and support of SQL queries in the entity beans. A new EntityManager API similar to Hibernate and a simplified version of TopLink’ Session API is being proposed to manipulation of entity beans i.e. creation, removal, finding of entity beans.

We will closely examine the details of the proposed CMP entity beans in a followup article.

Simplifying Client View for EJBs

Using EJBs i.e. to lookup and invoke is very complex even if EJB is collocated in the application. J2EE 1.4 and EJB 3.0 spec is working on to simplify the client’s view of EJBs.

If you want to use an EJB presently you have to define the ejb-ref or ejb-local-ref in the deployment descriptor, lookup the EJB and then invoke. If we want to invoke our HelloWorld EJB, following is the simplest way you can invoke an EJB with the current implementation.

First define the EJB references in the deployment descriptor as follows:

<ejb-ref>

<ejb-ref-name>HelloWorldEJB</ejb-ref-name>

<ejb-ref-type>Session</ejb-ref-type>

<home>hello.HelloWorldHome</home>

<remote> hello.HelloWorld</remote>

</ejb-ref>

Then lookup the EJB as follows. You have to explicitly handle exceptions for EJB lookup and creation of a bean instance.

try

{

Context context = new InitialContext();

HelloWorldHome helloHome =

(HelloWorld)PortableRemoteObject.narrow(context.lookup

(“java:comp/env/ejb/HelloWorldEJB”), HelloWorldHome.class);

HelloWorld hello = helloHome.create();

….

}

catch(RemoteException e)

{

System.err.println(“System/communication error: ” + e.getMessage());

}

catch(NamingException e)

{

System.err.println(“Communication error: ” + e.getMessage());

}

catch(CreateException e)

{

System.err.println(“Error creating EJB instance: ” + e.getMessage());

}

As an alternative to environment variables, EJB 3.0 proposes a way to use setter injection to lookup and invoke EJBs.

Following is way our HelloWorldEJB can be looked up in another EJB by using setter injection.

@Inject private void setSessionContext(SessionContext ctx)

{

this.ctx = ctx

}

myHello = (HelloWorld)ctx.lookup(“java:comp/env/ejb/HelloWorldEJB”);

If you look at the code above carefully the setSessionContext method is annotated with @Inject to specify that dependency injection be used for this method. The injected methods will be invoked by the container to set the EJBContext before any business method be called on that EJB.

Another direct example to inject the HelloWorld session bean would be to simply have @EJB public HelloWorld myHello and this would cause myHello to be injected with an instance of the HelloWorld bean.

You can use dependency injection to lookup any type of environment and resource references such as DataSource, JMS, Mail, Web Service, etc.

Testability Usability Outside Container

A major concern for the current EJB developers is not only development of EJBs is complex but also testing is a nightmare. An EJB container is required is to develop and test the EJBs and the developers have to be familiar with the final deployment platform to perform testing. This may not be a major issue for many enterprise developers but is an issue for ISVs who work on supporting multiple vendors and they have to maintain multiple environments to do the testing of their EJBs. The EJB 3.0 spec promises to provide the ability to test outside the container but this is currently missing in the draft specification.

Conclusion

Although there are a lot of missing information about packaging, assembly and gory details of APIs, the proposals made in EJB 3.0 drafts looks very promising for enterprise java developers. These will certainly help remove the complexities from developers view by passing those to the container vendors. It is to be seen how the container vendors implement these and make EJB 3.0 a compelling option to develop enterprise applications.

References and further reading

Permalink Leave a Comment

Inheritance & EJBs

April 30, 2008 at 12:45 pm (EJB, Extra) ()

By Daniel O’Connor


June 2002

Discuss this Article

Introduction

One of the most common criticisms of entity EJBs is that they don’t support inheritance or polymorphism. If this were true, it would be a serious complaint for two reasons. First, entity beans are intended to provide an object-oriented view of information in a persistent store, and inheritance and polymorphism are key aspects of the object-oriented programming paradigm. Second, many bean developers are using relational database schemas that essentially implement a form of inheritance, and they need to be able to operate on these schemas with their EJBs. However, in practice, entity EJBs are capable of meeting these requirements.

In this article I’m going to show how to implement entity bean inheritance with three CMP EJBs: a “base class” PARTY EJB and two “derived class” EJBs: PERSON and CORPORATION. (This is a common design in relational database schemas.) Furthermore, I’ll demonstrate a polymorphic finder query and a couple of polymorphic method calls. The beans I produce will be absolutely portable according to the EJB 2.0 specification.

I’ll also show how these container-managed persistence beans can be mapped to a standard relational database schema for this type of data. The EJB specification does not require particular object/relational mapping capabilities from an EJB container’s CMP engine. It does not even require that the container be able to use relational databases at all, so the ability to map to a particular schema is not portable. However, I am the author of a pluggable CMP engine that provides this capability (the MVCSoft Persistence Manager). We’ll look at how this engine is able to make the sometimes-difficult translation from EJB objects and relationships to database tables, and what is involved from the user’s point of view in using this particular mapping.

Some Distinctions

It’s important to be clear exactly what we mean when we talk about inheritance. In this case there are three possibilities, and this article is mostly about a single one of these possibilities. First, there is the language inheritance with which every competent Java programmer is familiar. The Java language allows a class to extend a single immediate base class, which can in its turn extend another single base class, until the universal base class of java.lang.Object is reached. It also allows an interface to extend one or more interfaces. Finally, it allows a class to implement any number of interfaces. The EJB specification allows for any of the interfaces or implementation classes associated with a bean (remote home and component interfaces, local home and component interfaces, primary key class, and bean implementation class) to take advantage of these Java language features. (There are a few caveats, such as requirements for the return types from create methods.)

Second, there is an amorphous concept called “component inheritance.” Although frequently used (even once in the EJB spec itself), there is no generally accepted definition of the term in this context. It would probably include (1) the ability to extend an existing entity without modifying the base component or even having the source code; (2) the ability to compare component interfaces of different types for equality; and (3) the ability to return different component interfaces from a single finder or ejbSelect method.

Third, there is “data model inheritance.” This is the ability to model an inheritance hierarchy of business objects (and their polymorphic behavior) using entity EJBs. It is this last type of inheritance that this article addresses. Note that whereas language inheritance and component inheritance might be considered “implementation details,” data model inheritance directly affects what can and cannot be accomplished using EJBs.

Why the Criticism?

If entity EJBs are capable of inheritance and polymorphism, why do people frequently say they are not? One source for this criticism can be found right in the EJB 2.0 specification. Section 11.2.11 says, “The data model for container-managed persistence does not currently support inheritance. Therefore, entity objects or value classes of different types cannot be compared. EJB QL queries that contain such comparisons are invalid.” Furthermore, the list of features deferred to future releases includes “support for component-level inheritance.”

In fact, there is no framework support in the EJB spec for inheritance and polymorphism. This has consequences for all three types of inheritance discussed above. It makes component inheritance–by any reasonable definition–impossible. It places limitations on how language inheritance is used. It requires the bean developer to implement data model inheritance on his or her own, while being mindful of the limitations of the EJB component model. This lack of framework support, and the consequences, are the issues that ultimately generate the criticism.

But that’s a far cry from saying that entity EJBs are incapable of representing an inheritance hierarchy, or polymorphic behavior, in a data model. When enterprise software developers hear about the lack of inheritance in EJBs, they most likely assume that EJBs cannot work with their existing schema. But they can, and this is the important point by far. In practice, it’s not that significant that you don’t have “black box” component-level inheritance for EJBs. What’s important is that you can represent your complete existing enterprise schema using EJBs.

How to Do It

It’s not complicated to implement a schema incorporating inheritance. The fundamental technique is called “containment.” This just means that your base EJB component will have a reference to its derived class or classes, and will delegate calls as appropriate. The base class will need some way of determining how to delegate the call to a related “derived” class. Typically, there will be a field (called a discriminator) that establishes the type of the base class. In its simplest form, a business method would check this discriminator, retrieve the appropriate related entity component interface from a cmr field, and delegate the call to this interface. For example, a business method call on a PARTY component interface would be translated by the container to a call on the PARTY implementation class. The PARTY implementation class might check a discriminator CMP field, and depending on the result, delegate the business method call to the PERSON cmr field or the CORPORATION cmr field.

Polymorphic relationships between entities will actually be between base EJB components, and polymorphic EJB-QL queries will return references to the base EJB component. For instance, if there were an ORDER component, it might have a relationship to a PARTY bean, rather than either a PERSON or CORPORATION bean. Or if you called a finder that retrieved all the orders in Ohio, you would query on the PARTY bean rather than the PERSON or CORPORATION bean.

It is possible that there might be methods defined on a subclass component interface that aren’t defined on the base component interface. You can’t use Java language casting to downcast from the base interface to the subclass interface…but you could implement a business method that returned the desired derived component interface. An elegant signature might be EJBLocalObject dynamicCast( String type ).

The example code for this article implements four EJBs: a session bean fafacadeade and the three entity EJBs (PARTY, PERSON, and CORPORATION). A client will ask the session bean facade to create some sample data: three people and three corporations. It will then execute a findAll() query that returns all six of these EJBs in a single result set. It will call two polymorphic business methods, one getting a display name and one getting a credit rating. There is nothing special about any of the code, but I’ll review the parts that are relevant to inheritance or polymorphism.

First, I have provided a business interface from which every local component interface in the inheritance hierarchy derives. (See PartyIntf.java.) This is not a requirement, but it allows us to treat any local component interface in the hierarchy as a single type with polymorhic methods. If I had not done this, the business methods of all three of the component interfaces would still function correctly, but the client would not be able to treat a party component interface, a person component interface, and a corporation component interface as the same type. Really, this is just syntactic sugar.

In this example, the polymorphic behavior is implemented entirely in the PARTY bean implementation class. (See PartyBean.java.) There is a cmp field “typeCode” that indicates the derived type of the entity. There are also two cmr fields to contain the derived instance: corporation and person. In this example, they are mutually exclusive and one of them will be null, but this is not a fundamental requirement. (In other words, you can implement multiple inheritance if your schema requires it.)

There are two business methods: getDisplayName() and getCreditLimitCode(). When either of the business methods is called, the typeCode cmp field is checked and the business method is delegated appropriately. For example:

public String getDisplayName()

{

String code = getTypeCode();

if (code.equals(“I”))

return getPerson().getDisplayName();

else if (code.equals(“C”))

return getCorporation().getDisplayName();

throw new EJBException( “Unknown type” );

}

You could make a case that the typeCode is redundant and it should be possible to check which relationship is not null. But if the cmr field is being lazily loaded by the EJB container, this could result in unnecessary database I/O.

The findAll() query (used by the session bean facade and called by the client) is defined on the PARTY local home interface. Of course, it is only returning component interfaces for the PARTY EJB, but these represent both PERSON instances and CORPORATION instances. It is defined in the deployment descriptor as a query returning PARTY instances, as follows:

<query>

<query-method>

<method-name>findAll</method-name>

<method-params/>

</query-method>

<ejb-ql>select object(pb) from PartyBean pb</ejb-ql>

</query>

The last interesting pieces of code from this example are the ejbCreate and ejbPostCreate methods for the CORPORATION and PERSON beans. As well as creating the corporation or person instance, respectively, these methods need to create the corresponding PARTY instance and establish a one-one relationship between the two. You might wonder if any special technique is required, considering that the relationship between a PARTY instance and a CORPORATION or PERSON instance is likely implied by a migrated key, rather than being explicitly stored in a separate foreign key. But this is a detail of the object/relational mapping, and doesn’t enter into consideration when you are coding your component. Let’s take a look at CorporationBean.java’s ejbCreate method:

public Integer ejbCreate( ViewCorporation view )

throws CreateException

{

getPartyLocalHome().create(new ViewParty(view.getId(), “C”));

setViewCorporation( view );

return null;

}

This is just one possible implementation, but the basic steps will usually be the same. In the ejbCreate method, we create an instance of the PARTY base component, and initialize the cmp fields for this component. Then in the ejbPostCreate method, we establish the relationship between the two:

public void ejbPostCreate( ViewCorporation view )

throws CreateException

{

try

{

PartyLocal party = getPartyLocalHome().findByPrimaryKey(view.getId());

setParty( party );

}

catch (FinderException e)

{

throw new EJBException( “Party not created” );

}

}

Object/Relational Mapping

For most enterprise developers, modeling inheritance and polymorphic behavior in EJBs is just half the battle. The other half is working with an existing schema. The code with this article should work with any EJB container, but there are no requirements in the EJB spec for any set of mapping capabilities. In practice, you’ll find that there is substantial variation in capabilities between implementations, and there are three potential trouble spots here.

First, the most common database schema for this model will have a migrated primary key that establishes the relationship between the base and derived entities. In the EJB world, primary keys and relationships are completely unrelated. The persistence mechanism for your EJB container must be smart enough to realize that in this case, the primary key and relationship information in the persistent store are conflated.

Second, the typical database schema for this model will have foreign-key constraints on the migrated primary key. This requires that the database inserts take place in the correct order (to not violate these constraints). If the EJB container triggers the insert statements immediately on return from ejbCreate, you must make sure that your code is ordered correctly. The persistence manager I wrote (the MVCSoft Persistence Manager) can cache the data and write it out to the database at the end of the transaction, dynamically reordering the database i/o so as to not violate any constraints.

Finally, if your EJB container is lazily-loading relationships for large result sets, it can lead to unacceptable performance. In our example, each call from the PARTY bean to getCorporation() or getPerson() might result in a select query to the database to get the information. There are several possible solutions to this problem. For example, the MVCSoft Persistence Manager allows you to define a “fault group” for a query that defines the information you will need during the transaction, and this fault group can extend to related information. The runtime will eagerly load the required data using a minimum number of queries. If you issued a finder query that returned a hundred results and called a polymorphic method on each instance, a properly configured runtime will issue three queries, rather than 101 queries as in the lazy loading case.

Conclusion

Despite what you may have heard, entity EJBs can be used effectively to represent business objects with inheritance and polymorphic behavior. There is no support for this functionality in the EJB component model, but one simple technique–called containment–is to delegate polymorphic business method calls to appropriate “derived” component instances. The EJB specification does not mandate specific object/relational mapping functionality, but there are products that can work with your existing relational database schema.

Permalink Leave a Comment

Deciding whether EJB is appropriate

April 30, 2008 at 12:41 pm (EJB, Extra) ()

By Ed Roman

excerpted from the new “Mastering Enterprise JavaBeans 2nd edition” book
September 2001

Discuss Article here.

Motivation

A recent Gartner Group report cited companies overspent $1 billion on EJB last year, when they could have just gotten by with Servlets/JSPs. This motivates our next discussion: once you’ve decided whether server-side Java is the way to go, you then need to make the all-important decision: are you actually going to use EJB on this project? Or is EJB overkill?

Example

As a motivational example, consider an E-commerce site that has involved business processes. When you buy something on an E-Commerce site, the site needs to:

  • Validate your credit card
  • Debit your credit card
  • Perhaps run some anti-fraud checking algorithms
  • Check inventory
  • Send a confirmation email
  • Submit the order
  • Fulfill the order
  • Track the order afterwards
  • Handle returns

You can still achieve all of this by using vanilla Servlets and JSPs. For example, you could have the Servlets and JSPs call Java classes. Those Java classes perform your business logic. In fact, there are three scenarios that we can consider when it’s possible to use Java classes rather than EJB components:

In a browser client web-based system with Servlets and JSPs, you could use Java classes rather than EJB components.

In a web services system where business partners call your Servlets and JSPs using XML/HTTP, you can also use Java classes rather than EJB components (see for a whitepaper on how to build web services using J2EE).

In a 2-tier client/server system such as a Java applet or Java application connecting to a server, you could again use Servlets and JSPs on the server. The thick client could communicate with the server via HTTP, which easily navigates through firewalls (compared to IIOP, which doesn’t). Behind the Servlets and JSPs could be Java classes instead of EJB components.

NOTE: A Servlet/JSP HTTP layer is only important if the users of your system are going to be behind firewalls, such as anonymous Internet clients, business partners, or other departments within your organization. It’s also important if your thick client is located across the Internet, because HTTP is a lightweight protocol that travels across the Internet easily. If there is no firewall issue, or if your users are not located across the Internet (but rather are on your local area network) you could get rid of your HTTP layer and connect the client to EJB components directly. In this case, the EJB value proposition is very strong, because EJB allows the client to call the server using intuitive method names, removes the need to perform XML marshaling, and gives you automatic remotability and load-balancing.

The Fear, Uncertainty, and Doubt

So how do you decide which is the right paradigm? Let’s start out with the reasons that most people think are important for deciding between EJB and Java classes, but are actually not important at all.

EJB server cost. The major J2EE server vendors, such as IBM, BEA, and Oracle, do not sell their EJB layer separately from their Servlet/JSP layer. They sell a single “J2EE server” which bundles both layers. So if you go with a market leader, then you’re probably going to buy an EJB server whether you like it or not. The only way to avoid this cost is to purchase an open-source or inexpensive Servlet/JSP implementation. This is a viable option, this is not recommended for major deployments. Why? Because the cost of the J2EE server is often a drop in the bucket compared to the total cost of the project. If the server doesn’t work out, consider all the retraining you’ll need to pay for, and the code you may need to rewrite if the servers use different versions of the J2EE specifications. Consider the difficulty in hiring skilled professionals if you don’t go with a market leader, the cost of re-learning how to tune your new server, and the cost of learning how to administer that new server. The cost of the application server should not be an issue for most serious deployments–most major vendors are charging very reasonable fees, far less than the $50,000 per processor that was charged back in the day. Rather, you should consider whether an EJB layer or a Java class layer is appropriate for your project. The professional services fees–we call it geek time–tends to dwarf the application server cost.

Resource pooling. Some people think that only EJB can give you resource pooling. Not true. Almost all the major J2EE server vendors allow you to get connection pooling and thread pooling whether you use Servlets/JSPs or EJB components.

Clean separation of business logic and presentation logic. EJB is nice because it enforces a separation of presentation logic (Servlets and JSPs) from business logic (EJB components). We like this because in the future we can support different types of presentation logic, such as a WAP enabled phone, or an XML data stream client from a business partner. But you can achieve the same results with Java classes instead of EJB components as well. You just need to enforce some coding best-practices in your organization about the proper usage of Java classes as a business layer facade.

Deciding the right way

Now that we’ve blown away the FUD (Fear, Uncertainty, and Doubt), here are the real reasons to use EJB over Java classes:

Your system is built faster and more reliably. EJB components benefit from declarative middleware, such as instance pooling, transactions, security, container-managed persistence, container-managed relationships, and data caching. If you used regular Java classes, you’d need to write this middleware yourself over time. Eventually you might find that you have your own middleware framework. That ‘framework’ is a fancy word for building your own home-grown application server. The framework needs to be tested, debugged, features need to be added. This is a non-trivial task indeed. Can you honestly state that your staff is capable of building a better application server than the market leaders who specialize in middleware?

It is easier to hire new employees. If you build your own custom framework using Java classes, then newhires need to be trained on this framework. If your framework is complex, then you can no longer look for “EJB” on a resume when hiring a developer and expect them to be productive on your system.

You benefit from the best practices the world is building around EJB. You can figure out how to optimize your system by reading articles on the Internet, or picking up a book on EJB best practices, such as Floyd Marinescu’s “EJB Design Patterns” book. This global knowledge base is not at your disposal with a proprietary Java class framework.

You can have different user interfaces. You can reuse the same EJB component layer for a thick client as well as a Servlet/JSP client. With Java classes, you cannot achieve this because Java classes are not remotely accessible. If you wrapped those Java classes in RMI objects, you’d need to invent your own load-balancing, instance pooling, and fail-over.

You can work with industry-standard tools to rapidly develop your system. While in the short run you may think that Java classes are going to make it faster to develop than writing all those files that comprise an EJB component, in reality there are many tools around that help streamline the EJB development process. There are command-line tools that generate the files you need, there are IDEs that help you build EJB components, and there are UML editors that help you generate EJB components from UML diagrams. See for more.

You can separate your web tier and application server. If you require your business logic to be protected by a firewall, then you can deploy the web server and application server on separate machines and stick a firewall in the middle.

And here are the real reasons not to use EJB:

You can’t deal with the limitations of EJB. Examples include threading, static variables, and native code. Most companies can deal with this, because there are good reasons why the restrictions exist. But if (for example) you need to have a multi-threaded engine, and you can’t deal with the EJB paradigm of load-balancing across single-threaded instances, then EJB is not a good fit for you. EJB is a square peg–don’t try to stick it into a round hole.

Your have existing skillsets or investments in a working technology. For example, if your developers are proficient in CORBA, then great–why not stick with it? As an anecdote, The Middleware Company consulted with one of our clients who wrote a CORBA application that assisted with mapping the human genome. It worked well with CORBA, and they had no major complaints, and so we recommended they stick with CORBA and avoid the EJB hype.

Your application is a big GUI to a database. If you are just a big GUI to a database–heavy on data logic but no business logic–you could achieve a deployment easily using JSPs with tag libraries connecting to a database via JDBC.

Your application is simple. If you are prototyping, building a simple system, or developing a one-off application that will not evolve over time, EJB may be overkill.

Permalink Leave a Comment

Next page »