There are times when handling of data transaction requires a little craftiness where transaction begins, commits and rollbacks could not be a straight-forward one. This is the time when Bean-Managed Transaction comes to play for business process that requires some lengthy customized units of transaction.

Today, I gonna write an article/tutorial on leveraging Bean-Managed transaction through the Java EE or JEE way for the benifit of myself (yes, I am pretty forgetful and I need to keep notes for back reference) and for those who are new in programming JPA in Java EE. I won’t touch on the basics of Database ACID Transaction, Two-Phase Commit Protocol or any other technicalities of that sort. You can always spend sometime reading these from other sites. But as far as this article is concern, it is about getting things to work as quick as possible.



How to Perform a Bean-Managed Transaction

In the Java EE context, you can have custom defined transactions in either the Stateless Session Bean or the Stateful Session Bean. The below are a few quick sequence of setup to get Bean-Managed Transaction up and running:

  1. Make sure that you are using the right JDBC driver for the Application Server and set up correctly.Some JDBC Drivers are XA drivers that supports Two-Phase Commit and some are not. For example MySQL has DataSource classes like com.mysql.jdbc.jdbc2.optional.MysqlDataSource and com.mysql.jdbc.jdbc2.optional.MysqlXADataSource. Please chooce them wisely. For a list of JDBC Drivers, please refer to: http://docs.oracle.com/cd/E19798-01/821-1751/ghhvc/index.html

    ** Please take note that for MySQL database, make sure that tables are using the InnoDB engine instead of the MyISAM engine. If not, transaction will never work.

  2. Configure the persistence.xml fileIn the tag, make sure you include the attribute transaction-type and set the value to “JTA”. For example:

  • Preparing the Session Bean:In the session bean, you need to mark the class with the @javax.ejb.TransactionManagement annotation and set the TransactionManagementType to javax.ejb.TransactionManagementType.BEAN. As you proceed, please define the persistence manager and the EJB context like the example below:
  • For methods in the Session Bean within a transaction context, get the UserTransactioninstance from the EJBContext and invoke begin(), commit() and rollback() at the necessary point:

A Simple Transaction Use Case Demo

Here, I’ll show you a comprehensive use case when transaction is required and where manual begin, commit and rollback is necessary. This use case is about the transfer of funds from a bank savings account to a checking account…something that we do most of the time. It won’t be too elaborated like what’s currently being deployed in the banking system, but it is good enough to illustrate times when elaborated control of transaction is required. The below is the database diagram of tables, accompanied by the SQL scripts for MySQL DB that generates the tables which are involve in the transfer of funds from a savings account to a checking account. Both accounts can and will belong to a single customer. It is an inter-account transfer by the way.

Bank Account Fund Transfer Database Tables
Bean-Managed Transaction Bank Funds Transfer DB Diagram

Tables and Use Case Description

The tables diagram only consists of several tables that are related to perform the fund transfer. It is very watered-down and superficial; but for now, it is sufficient to capture the related entities.

Table NameEntity Class NameDescription
BANK_CUSTOMERSBankCustomerEntityThe customer record of the bank. For simplicity, we only capture both username and password field.

** In this demo, we’ll set the username and password are both “MadMax” and “passwd123”

BANK_ACCT_TYPEBankAcctTypeEntityThis is more like a statis data table which consists of various bank account types. For now, only “SAVINGS” and “CHECKING” account type is available. Please look at the data population script below.
BANK_ACCOUNTBankAccountEntityThe bank account of customers. It has fields like account no., the current balance, the foreign key will tie to the BANK_CUSTOMERS table to identify the ownership of the account. Both SAVINGS and CHECKING accounts are within this table. One customer could have multiple accounts.

** In this demo, “MadMax” has a savings account BK-001-09 with the balance of $9,000,000 and a checking account BK-012-10 with the balance of $1,000,000.

ACTIVITY_LOGActivityLogEntityThis is a table that records all of the activity of the customer with a timestamp when they perform a transaction and whether the transaction is a success or a failure.

** So, everytime when “MadMax” performs a transaction whether it goes through or not, the system will insert the record here as an activity log in this table.

BANK_GROUP_PROFITBankGroupProfitEntityThis table captures the profit (service charge/commission) made by the bank’s branch whenever a customer performs a transaction.

** For demo purposes, let’s have the bank’s initial balance of the profit to be $1bil and bank commission fixed at $2 for every fund transfer transaction performed. This $2 will be added upon the profit balance.

The SQL script for generating the tables as well as pre-populating the database with data is shown below. This script is for MySQL DB only. However if you are running on other database platform, you should be able to come out with your own script for experiment purposes by referring to the below:

MySQL Database Tables and Data Script

Codes for ActivityLogEntity

Codes for BankAcctTypeEntity

Codes for BankAccountEntity

Codes for IBankTransactionSessionFacadeLocal

Testing The Transaction Process

You may always write snippet of codes to test the transaction like the below:

Do play around with the value in transferAmount, the fromAccountNo and the toAccountNo and check for the validity of data in the database, you should be able to see the transaction in action.

Summary

I do hope that you are able to get a kick start with EJB3.x Bean-Managed transaction with this page. Bean-Managed transaction is always prefered when there are data to be persisted in a controled pre-defined way. But at the same time, do use Bean-Managed transaction wisely as the more power of control it gives to you, the more that you need to handle it well. This article is just the tip of the ice berg of transaction, you may want to further explore topics like locking mechanism and transaction high availability/clustering environment, which are quite challenging to managed and it will affect the behaviour of the application.

Hope you’ve enjoyed.

Related Articles

Max Lam
About the Author

Born and currently resides in Malaysia, a seasoned Java developer whom had held positions as Senior Developer, Consultant and Technical Architect in various enterprise software development companies.

Related Posts

(adsbygoogle = window.adsbygoogle || []).push({}); This is a quick guide on how to install a...

This is the last part in the series of “Making sense of EJB3.x Transaction Attributes“. So far,...

Oracle had extensively documented the behavior of each transaction attributes in the Java EE...