ejb-3.0spring-transactionsspring-mybatistransactionmanager

TransactionManagementType.CONTAINER vs TransactionManagementType.BEAN


what is the difference between TransactionManagementType.CONTAINER and TransactionManagementType.BEAN

as Im using TransactionManagementType.CONTAINER in all of my EJBs and when ever the multiple instances of database is used, It throws an error which gets resolved if i change it to TransactionManagementType.BEAN

I want to know what are the advantages and disadvantages and how it gets effected if I change it to TransactionManagementType.BEAN

ERROR:
Error updating database.  Cause: java.sql.SQLException: javax.resource.ResourceException: 
IJ000457: Unchecked throwable in managedConnectionReconnected() cl=org.jboss.jca.core.
connectionmanager.listener.TxConnectionListener@680f2be0[state=NORMAL managed 
connection=org.jboss.jca.adapters.jdbc.local.LocalManagedConnection@7ba33a94 connection 
handles=0 lastReturned=1495691675021 lastValidated=1495690817487 
lastCheckedOut=1495691675018 trackByTx=false pool=org.jboss.jca.core.connectionmanager.
pool.strategy.OnePool@efd42c4 mcp=SemaphoreConcurrentLinkedQueueManagedConnectionPool
@71656eec[pool=FAQuery] xaResource=LocalXAResourceImpl@4c786e85
[connectionListener=680f2be0 connectionManager=5c3b98bc warned=false 
currentXid=null productName=Oracle productVersion=Oracle Database 12c 
Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options
jndiName=java:/FAQuery] txSync=null]

Solution

  • TransactionManagementType.CONTAINER

    You let the container itself manage transactions(container will commit and rollback). You can control behavior of your transactions (more precisely transaction propagation) by annotating methods with @TransactionManagementAttribute and specifying one of the attributes from TransactionAttribute Types.

    TransactionManagementType.BEAN

    You have to do transaction demarcation (start, commit, rollback) explicitly yourself, by obtaining UserTransaction interface.

    @Resource
    UserTransaction ut;
    
    public void method(){
       ut.begin();
    ... // your business logic here
       ut.commit(); // or ut.rollback();
    }
    

    Note that you have to either commit and rollback before you exit the same method which stated the transaction for Stateless and Message Driven Beans, but it is not required for Stateful bean.

    Regarding your question, advantage of BMT is that scope of the transaction can be less than scope of the method itself, i.e explicit control of the transaction. You would most probably use CMT, BMT is required only in some narrow corner cases to support specific business logic. Another advantage or use case of BMT is if you need to use Extended Persistence Context Type, which can be supported in BMT with Stateful Session Beans.