Welcome!

Java Authors: Carmen Gonzalez, Aater Suleman, Pat Romanski, Paige Leidig, Liz McMillan

Related Topics: Java

Java: Article

EJB 3 Transactions

Understanding and using transactions with EJB 3

Much of the work surrounding the design and development of enterprise applications involves decisions about how to coordinate the flow of persistent data. This includes when and where to cache data, when to apply it to a persistent store (typically the database), how to resolve simultaneous attempts to access the same data and how to resolve errors that might occur while data in the database is in an inconsistent state. A reliable database is capable of handling these issues at a low level in the database tier, but these same issues can exist in the middle (application server) and client tiers as well, and typically require special application logic. One of the principal benefits of using EJB 3 is its support for enterprise-wide services like transaction management and security control. In this article, we will explore how EJB 3 offers transaction services and how you can leverage them to meet your specific requirements.

Understanding Transactions
A transaction is a group of operations that must be performed as a unit. These operations can be synchronous or asynchronous, and can involve persisting data objects, sending mail, validating credit cards, etc. A classic example is a banking transfer, in which one operation debits funds from one account (i.e., updates a record in a database table) and another operation credits those same funds to another account (updates another row in that same, or a different database table). From the perspective of an external application querying both accounts, there must never be a time when these funds can be seen in both accounts. Nor can a moment exist when the funds can be seen in neither account. Only when both operations in this transaction have been successfully performed can the changes be visible from another application context. A group of operations that must be performed together in this way as a unit is known as a transaction.

When the operations in a transaction are performed across databases or other resources that reside on separate computers or processes, this is known as a distributed transaction. Such enterprise-wide transactions require special coordination between the resources involved and can be extremely difficult to program reliably. This is where Java Transaction API (JTA) comes in, providing the interface that resources can implement and to which they can bind, in order to participate in a distributed transaction. The EJB container is a transaction manager that supports JTA and so can participate in distributed transactions involving other EJB containers, as well as third-party JTA resources like many database management systems (DBMS).

The ACID Properties of a Transaction
Transactions come in all shapes and sizes and can involve synchronous and asynchronous operations, but they all have some core features in common, known as their ACID components. ACID refers to the four characteristics that define a robust and reliable transaction: atomicity, consistency, isolation, and durability. Table 1 describes these four components.

EJB 3 addresses these requirements by providing a robust JTA transaction manager and a declarative metadata API that can be specified on interoperable, portable business components. Virtually all Java EE applications require transaction services and EJB brings them to the application developer in a very slick package. From its inception, the EJB framework has provided a convenient way to manage transactions and access control by letting the developer define the behavior declaratively on a method-by-method basis. Beyond these container-provided services, EJB 3 allows developers to turn control over to the application to define transaction event boundaries and other custom behavior.

EJB 3 Transaction Services
The EJB 3 transaction model is built on this JTA model, in which session beans or other application clients provide the transactional context in which enterprise services are performed as a logical unit of work. Enterprise services in the Java EE environment include the creation, retrieval, updating and deletion of entities; the sending of JMS messages to the queue; the execution of MDBs; the firing of mail requests; the invocation of web services; and JDBC operations.

EJB 3 provides a built-in JTA transaction manager, but the real power lies in the declarative services EJB offers to bean providers. Using metadata tags instead of programmatic logic, bean providers can seamlessly participate in JTA transactions and declaratively control the transactional behavior of each business method on an enterprise bean. EJB 3 extends this programming model by providing explicit support for both JTA transactions and non-JTA (resource-local) transactions. Resource-local transactions are restricted to a single resource manager, such as a database connection, but may result in a performance optimization by avoiding the overhead of a distributed transaction monitor. In addition, application builders may leverage the container-provided (JTA-based) services for automatically managing transactions, or they may choose to take control of the transaction boundaries and handle the transaction begin, commit and rollback events explicitly. Within a single application, both approaches may be used alone or in combination if desired. Whereas the choice of whether to have the container or the application itself demarcate transactions is defined on the enterprise bean, the decision of which type of transaction model to use - JTA or resource-local - is determined when a given EntityManager is obtained from within an application. The persistent objects in the game - the entities - are entirely, and happily, unaware of their governing transaction framework. The transactional context in which an entity operates is not part of its definition, so the same entity class may be used in whatever transactional context the application chooses, provided an appropriate EntityManager is created to service the entity's life cycle events.

The EJB 3 container offers declarative demarcation of transaction events, along with the option to demarcate transaction events explicitly in the bean or in the application client code. Let's consider these two approaches separately, beginning with the default option: leveraging container-managed transaction (CMT) demarcation using declarative markup.

Container-Managed Transaction (CMT) Demarcation
EJB 3 provides built-in transaction management services that are available by default to session beans and MDBs. The container demarcates transaction boundaries and automatically begins and commits transactions based on declarative metadata provided by the bean developer.

When an EJB declares its transactional behavior in metadata, the container interposes on calls to the enterprise bean's methods and applies transactional behavior at the session bean's method boundaries. One of a fixed set of options may be specified for each method. The default behavior provided by the container is to check, immediately before invoking the method, whether a transaction context is associated with the current thread. If no transaction context is available, the container begins a new transaction before calling the method. If a transaction is available, the container allows that transaction to be propagated to the method call and made available to the method code. Then, upon returning from the method invocation, the container checks again. If the container was responsible for creating a new transaction context, it automatically commits that transaction after the method is exited (or, if an exception is thrown by that method, it rolls back the transaction it began). If it did not create the transaction, then it allows the transaction to continue unaffected. By interposing on the bean's method calls, the EJB container is able to apply transactional behavior at run time that was specified declaratively at development time.

The default behavior described above is specified by the REQUIRED transaction attribute. You can attribute any one of the six demarcation options shown in Table 2 to any method on a session bean.

All six attributes are typically available for session bean methods, though certain attributes are not available on a session timeout callback method, or when the session bean implements javax.ejb.SessionSynchronization. MDBs support only the REQUIRED and NOT_SUPPORTED attributes. Here is an example of how you would specify the transaction behavior on a session bean method to override the transaction behavior specified (or defaulted) at the bean level:

@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public CustomerOrder createCustomerOrderUsingSupports(Customer customer)
throws Exception { ... }

Table 3 illustrates an EJB's transactional behavior, dependent on its transaction attribute and the presence or absence of a transactional context at the time the session method is called.

Bean-Managed Transaction (BMT) Demarcation
For some enterprise beans, the declarative CMT services may not provide the demarcation granularity they require. For instance, a client may wish to call multiple methods on a session bean without having each method commit its work upon completion. In this case, the client has two options: it can either instantiate its own JTA (or resource-local) transaction, or it can ask the session bean to expose transaction demarcation methods that the client can call to control the transaction boundaries itself.

To address this latter requirement, EJB offers enterprise beans a convenient way to handle their demarcation of transaction events. To turn off the automatic CMT demarcation services, enterprise beans simply specify the @TransactionManagement(TransactionManagementType.BEAN) annotation or assign the equivalent metadata to the session bean in the ejb-jar.xml file. With BMT demarcation, the EJB container still provides the transaction support to the bean. The primary difference is that the bean makes explicit calls to begin, commit and roll back transactions instead of using CMT attributes to declaratively assign transactional behavior to its methods. Also, the container does not propagate transactions begun by a client to beans that elect to demarcate their own transactions. While any given enterprise bean must choose one plan or the other (CMT vs. BMT demarcation) for its methods, both types of beans may interact with each other within a single transaction context.

In the last part of this article, we discuss JPA entity transaction behavior.

How Entities Become Associated with a Transaction Context
From the preceding discussion about how the EJB server acts as a transaction coordinator in associating resources with a transaction context, you may have realized that a JPA entity's persistence context is the resource that gets associated with a transaction. In this way, a persistence context is propagated through method calls so entities in a persistence unit can see each other's intermediate state, through their common persistence context, if they are associated with the same transaction context. Also, the restriction that only one persistence context for any given persistence unit must be associated with a given transaction context ensures that for any entity of type T with identity I, its state will be represented by only one persistence context within any transaction context. Within an application thread, only one transaction context is available at any moment, but the EJB server is free to dissociate one persistence context from that thread and associate a new persistence context for the same persistence unit to satisfy transaction isolation boundaries. When the EJB server does this, the newly instantiated persistence context is not able to see the intermediate changes made to any entities associated with the suspended persistence context.

Container-Managed vs. Application-Managed Persistence Context
The persistence services in EJB 3 let you opt out of container-managed entity persistence altogether and manage the transaction life cycles of your entities explicitly within your application code. When an EntityManager is injected (or looked up through JNDI), it comes in as a container-managed persistence context. The container automatically associates container-managed persistence contexts with any transaction that happens to be in context at the time that the EntityManager is injected. Should an application wish to control how or whether its persistence contexts are associated with transactions, it may obtain an EntityManagerFactory (again, through container injection or JNDI lookup) and explicitly create the EntityManager instances that represent their persistence contexts. An application-managed persistence context is used when the EntityManager is obtained through an EntityManagerFactory-a requirement when running outside the Java EE container.

Transaction-Scoped Persistence Context vs. Extended Persistence Context
When an EntityManager is created, you may specify whether the persistence context that it manages should be bound to the life of a transaction, or whether it should span the life of the EntityManager itself. A persistence context that is created when a transaction is created, and destroyed when the transaction ends, is known as a transaction-scoped persistence context. A persistence context that is created at the time it is injected into the bean (or bound through a JNDI lookup), and is not destroyed until the EntityManager instance is itself destroyed, is called an extended persistence context. Only stateful session beans may use extended persistence contexts. At the time an EntityManager instance is created, its persistence context type is defined, and it may not be changed during the EntityManager's lifetime. The default type is transaction-scoped; to inject an EntityManager by specifying an extended persistence context, you may specify the injection directive with the following:

@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EnterpriseManager em;

or you may define a persistence-context-ref element in the XML descriptor.

Summary
In this article, we began with a discussion of the concepts essential to all transaction behavior, and we then explored both the built-in, declarative features offered by the EJB container, as well as options to bypass this support and coordinate transactions in application code. We concluded by describing the ways that JPA entities can interact with EJBs in a transactional environment.

Now that you are familiar with how to set up and use EJB 3 transactions, you may wish to explore the many related areas also introduced in the EJB 3 and JPA. For an examination of these features, with code samples, check out Beginning EJB 3 Application Development: From Novice to Professional (Apress, 2006).

More Stories By Raghu R. Kodali

Raghu R. Kodali is consulting product manager and SOA evangelist for Oracle Application Server. He leads next-generation SOA initiatives and J2EE feature sets for Oracle Application Server, with particular expertise in EJB, J2EE deployment, Web services, and BPEL. He holds a Masters degree in Computer Science and is a frequent speaker at technology conferences. Raghu is also a technical committee member for the OASIS SOA Blueprints specification, and a board member of Web Services SIG in OAUG. He maintains an active blog at Loosely Coupled Corner (www.jroller.com/page/raghukodali).

More Stories By Jonathan Wetherbee

Jon Wetherbee is a consulting engineer and tech lead for EJB development tools on Oracle's JDeveloper IDE. He has over 12 years of experience in development at Oracle, having built a variety of O/R mapping tools and holding responsibility for Oracle's core EJB toolset since EJB 1.1. In 1999, he received a patent for his work on integrating relational databases in an object-oriented environment.

Jon is co-author of 'Beginning EJB 3 Application Development: From Novice to Professional' (Apress, 2006), and enjoys speaking at user groups on EJB and related topics. Jon holds a BS in cognitive science from Brown University.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
ejm 10/15/08 10:29:07 AM EDT

Well versed article and nice explanation. Easy to understand especially for us who gives merchant services.

@ThingsExpo Stories
SYS-CON Events announced today that Harbinger Systems will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Harbinger Systems is a global company providing software technology services. Since 1990, Harbinger has developed a strong customer base worldwide. Its customers include software product companies ranging from hi-tech start-ups in Silicon Valley to leading product companies in the US and large in-house IT organizations.
The only place to be June 9-11 is Cloud Expo & @ThingsExpo 2015 East at the Javits Center in New York City. Join us there as delegates from all over the world come to listen to and engage with speakers & sponsors from the leading Cloud Computing, IoT & Big Data companies. Cloud Expo & @ThingsExpo are the leading events covering the booming market of Cloud Computing, IoT & Big Data for the enterprise. Speakers from all over the world will be hand-picked for their ability to explore the economic strategies that utility/cloud computing provides. Whether public, private, or in a hybrid form, clo...
SYS-CON Events announces a new pavilion on the Cloud Expo floor where WebRTC converges with the Internet of Things. Pavilion will showcase WebRTC and the Internet of Things. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices--computers, smartphones, tablets, and sensors – connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.
SYS-CON Events announced today that Gridstore™, the leader in software-defined storage (SDS) purpose-built for Windows Servers and Hyper-V, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Gridstore™ is the leader in software-defined storage purpose built for virtualization that is designed to accelerate applications in virtualized environments. Using its patented Server-Side Virtual Controller™ Technology (SVCT) to eliminate the I/O blender effect and accelerate applications Gridsto...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at Internet of @ThingsExpo, Andrew Bolwell, Director of Innovation for HP’s Printing and Personal Systems Group, will discuss how key attributes of mobile technology – touch input, senso...
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, will examine three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
The Internet of Things (IoT) promises to evolve the way the world does business; however, understanding how to apply it to your company can be a mystery. Most people struggle with understanding the potential business uses or tend to get caught up in the technology, resulting in solutions that fail to meet even minimum business goals. In his session at Internet of @ThingsExpo, Jesse Shiah, CEO / President / Co-Founder of AgilePoint Inc., will show what is needed to leverage the IoT to transform your business. He will discuss opportunities and challenges ahead for the IoT from a market and tec...
SYS-CON Events announced today that TeleStax, the main sponsor of Mobicents, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. TeleStax provides Open Source Communications software and services that facilitate the shift from legacy SS7 based IN networks to IP based LTE and IMS networks hosted on private (on-premise), hybrid or public clouds. TeleStax products include Restcomm, JSLEE, SMSC Gateway, USSD Gateway, SS7 Resource Adaptors, SIP Servlets, Rich Multimedia Services, Presence Services/RCS, Diame...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that O'Reilly Media has been named “Media Sponsor” of SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. O'Reilly Media spreads the knowledge of innovators through its books, online services, magazines, and conferences. Since 1978, O'Reilly Media has been a chronicler and catalyst of cutting-edge development, homing in on the technology trends that really matter and spurring their adoption by amplifying "faint signals" from the alpha geeks who are creating the future. An...
The Transparent Cloud-computing Consortium (abbreviation: T-Cloud Consortium) will conduct research activities into changes in the computing model as a result of collaboration between "device" and "cloud" and the creation of new value and markets through organic data processing High speed and high quality networks, and dramatic improvements in computer processing capabilities, have greatly changed the nature of applications and made the storing and processing of data on the network commonplace.
SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
As a disruptive technology, Web Real-Time Communication (WebRTC), which is an emerging standard of web communications, is redefining how brands and consumers communicate in real time. The on-going narrative around WebRTC has largely been around incorporating video, audio and chat functions to apps. In his session at Internet of @ThingsExpo, Alex Gouaillard, Founder and CTO of Temasys Communications, will look at a fourth element – data channels – and talk about its potential to move WebRTC beyond browsers and into the Internet of Things.
SYS-CON Events announced today that Gigaom Research has been named "Media Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Ashar Baig, Research Director, Cloud, at Gigaom Research, will also lead a Power Panel on the topic "Choosing the Right Cloud Option." Gigaom Research provides timely, in-depth analysis of emerging technologies for individual and corporate subscribers. Gigaom Research's network of 200+ independent analysts provides new content daily that bridges the gap between break...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
The Industrial Internet revolution is now underway, enabled by connected machines and billions of devices that communicate and collaborate. The massive amounts of Big Data requiring real-time analysis is flooding legacy IT systems and giving way to cloud environments that can handle the unpredictable workloads. Yet many barriers remain until we can fully realize the opportunities and benefits from the convergence of machines and devices with Big Data and the cloud, including interoperability, data security and privacy.