Should You Use EJBs?
This book assumes that you've already decided to use EJBs. However, in several instances, EJBs are not the best solution to a problem. It makes sense, therefore, to review where EJBs are strong and then discuss situations in which EJBs don't make as much sense. In several situationseven some enterprise database-centric applicationsEJBs are simply not the best choice. At the end of this section, we'll look at some of the alternative approaches and where they might fit.
When to Use EJBs
Here's a list of situations where EJBs are strong; we haven't distinguished between different types of EJBs:
Single and multisystem business transactions
-
The ability to maintain transactional integrity for complex business entities is one of an EJB's key strengths. EJBs aren't alone in providing straightforward transactional control over a single data repository. However, EJBs shine where multiple resources (relational databases, messaging systems, etc.) are involved because they allow transactions to spread across as many different resources as you like, so long as the resources support distributed transactions.
Distributed functionality
-
Business services often live on a remote server. For example, a business enterprise will have many different systems, ranging in degrees of inflexibility and entrenchment. One of these systems may need to access another. EJBs, which are inherently distributed, are often the simplest way to distribute remote services. EJB also allows you to provide business services to remote clients more easily than some alternatives. Remote access through components is easier to maintain than direct database access because the component code can shield the client from database schema changes.
Portable components (not classes)
-
Until recently, if you wanted to share your business services with another application developer, you were forced to share classes or at least packages. Java did not allow for the easy creation of enterprise components, or reusable software building blocks that can be assembled with other components to form an application. EJBs allow you to package your business logic into a tidy, distributable unit that can be shared in a loosely coupled fashion. The user of your component need only tweak a descriptor file for her environment.
Applications relying on asynchronous messaging
-
EJBs (specifically MDBs) provide a strong technology for handling asynchronous communication such as JMS-based messaging or web services.
Security roles
-
If your application's business operations can be mapped to specific business roles in your enterprise, then EJBs may be a good choice. So much is made of the transaction management capability of EJBs that their deployment-descriptor-based security management features are overlooked. This capability is very powerful; if your application's users fit into distinct roles and the rules for those roles dictate which users can write what data, EJBs are a good choice.
Persistence context management
-
Managing the life cycle of an EntityManager created by an EntityManagerFactory can become cumbersome. If you make any nested object method calls, you'll need to pass around the EntityManager instance as a parameter. Even if your application is simple, EJBs provide nice persistence context management that will shrink and simplify your code.
When Not to Use EJBs
In several situations when building a software applicationeven an "enterprise" software applicationusing EJBs may actually be a barrier to meeting your business goals. The following list represents places where you might not want to use EJBs:
Applications requiring thread control
-
If your application design requires extensive use of threads, then the EJB spec actually prevents you from using EJBs (although some EJB container vendors may provide nonportable ways around this restriction). Container systems manage resources, transactions, security, and other qualities of service using threads; threads you create are outside of the container's control and can potentially cause system failures. Also, EJB containers may distribute EJBs across multiple JVMs, preventing the synchronization of threads.
Performance
-
Because EJBs do so much more than plain Java classes, they are slower than plain Java classes. The EJB container has to do a lot: maintain transactional integrity, manage bean instances and the bean pools, enforce security roles, manage resources and resource pools, coordinate distributed operations, synchronize shared services (if the vendor offers clustering capabilities), and so on. In most applications, this overhead is extremely marginal, but if you're doing a lot of CPU-intensive operations, using EJBs may not be appropriate.
Database babysitting
-
Applications that just babysit a database may not need the nice persistence context control that EJBs provide because they are only doing monotonous database upgrades or batch processing. In this case, EJBs may be overkill.
Alternatives to EJBs
A few frameworks out there try to duplicate the functionality that EJBs provide. Here is the most popular:
Spring (http://www.springframework.org)
-
Spring pioneered many of the dependency injection concepts you see in the EJB 3.0 specification. However, it is a bit richer in functionality in this area in that entire object graphs can be represented in XML and injected into Spring-configured beans. The framework has much of the capabilities that EJB has to offer, such as integrated transaction demarcation and declarative security. It also provides a lot of integration helper classes that wrap some of the most popular open source frameworks out there. Spring also provides an integrated web framework similar to Struts and JSF. Spring is open source and available as a free download. The downside to Spring is that even though it is open source, it is controlled solely by one vendor. It is also entirely proprietary and not standards-based, as EJB is. Finally, although it has some annotation support, you'll find it very verbose in the XML department, so you'll need to really like XML deployment descriptors if you want to use Spring as your framework.
Alternatives to Java Persistence
There are a few alternatives to
Java Persistence; some of them are growing in popularity and maturity. Java Persistence and the old EJB CMP specification still rank as the de facto standards for enterprise transactional needs.
JDBC
The first (and likely most common) alternative to using Java Persistence is to write straight JDBC functions. Although JDBC was a viable alternative to EJB 2.1 CMP, Java Persistence and vendor-provided tooling actually make it much more worthwhile and productive to go with Java Persistence. Java Persistence has much of the power that straight SQL does, but it can provide all the caching layers and object population that are difficult to write by hand with JDBC. Given that Java Persistence can also be used outside of the application server, it even makes sense now for database applications that are one-off plain Java programs.
The situations in which straight JDBC is preferable to Java Persistence are not concrete. You should use straight JDBC when the need for speed outweighs the need for transactional support or security provided by Java Persistence. Here's a simple example that uses JDBC:
import java.sql.*;
public class JDBCExample {
public static void main(java.lang.String[] args) {
try {
// Load driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (ClassNotFoundException e) {
System.out.println("Cannot load driver.");
return;
}
try {
// Connect to database.
Connection con = DriverManager.getConnection("jdbc:odbc:contactdb",
"", "");
// Create SQL Statement and execute.
Statement stmt = con.createStatement( );
ResultSet rs = stmt.executeQuery("SELECT name FROM contacts");
// Display the SQL Results.
while(rs.next( )) {
System.out.println(rs.getString("name"));
}
// Release database resources.
rs.close( );
stmt.close( );
con.close( );
}
catch (SQLException se) {
// Display error message upon exception.
System.out.println("SQL Exception: " + se.getMessage( ));
se.printStackTrace(System.out);
}
}
}
JDBC is very straightforward; it allows you to access your data repository directly. However, you must understand a fair amount of the underlying mechanics (SQL, database connection properties, and so on) in order to use it. Now, in a "real" application using JDBC, you centralize most of this code into a few classes, but you still must write all the SQL yourself.
Others
There are, of course, alternatives to Java Persistence other than straight JDBC. Here are a few worth reviewing for suitability, should you determine that your application does not require Java Persistence or that certain requirements demand an alternative approach:
Hibernate (http://www.hibernate.org)
-
Hibernate is another Java class-to-database table mapping project. Although Hibernate is itself a Java Persistence open source project, it existed as a separate, well-established, and popular API long before Java Persistence existed. It is a superset of the Java Persistence specification and it has a richer API and toolset than the standard version. The founder of Hibernate, Gavin King, was one of the EJB 3.0 Expert Group members and brought the Hibernate project into the JCP process. You may have more complex mappings than EJB 3.0 persistence can handle, or you just may find the proprietary interfaces with which Hibernate works a bit more usable. If your company is not married to standards, using straight Hibernate APIs may be the way to go.
iBatis (http://ibatis.apache.org)
-
iBatis is another open source framework that allows you to map straight native SQL calls to Java classes. It is a bit different from Java Persistence in that instead of being a full O/R mapping with an object-specific query language, it maps SQL result sets directly into an object graph through an XML deployment descriptor. The advantages of this approach are that you can use it against stored procedures and complex vendor-specific SQL, and you can wrap it around legacy systems that are using JDBC to simplify and refactor the code. The downside of iBatis is that you lose a lot of the advantages that a full O/R tool gives you, such as automatic optimizations, caching, and an object query language. However, if you want to remain close to SQL but you have a cleaner abstraction to JDBC, iBatis is a fine solution.
JDO (http://java.sun.com/products/jdo)
-
JDO stands for Java Data Objects and is a JCP standard. Although it used to be a viable alternative to EJB 2.1 CMP, it is now a dead specification. A lot of the brains behind JDO, in conjunction with the minds behind JBoss's Hibernate and Oracle's Toplink products, were part of the Java Persistence specification efforts. Now that Java Persistence has been incorporated as part of the Java EE, JDO will probably be retired and a migration path to Java Persistence specified.
As you can see, there are a few alternatives to EJB and Java Persistence. If your application doesn't need the complexity or some of their features, take a look around. Data persistence, security, and distributed object components with Java have been around for some time, and a wide assortment of approaches exist.
|