Search code examples
jpatransactionsejbrollbackjta

Use JTA transaction with EJB and JPA


Hello everybody i'm looking for some help with the next problem: i have a jpa/stateless ejb's proyect that works perfectly, it just does simple queries and persist operations, but now i need to execute a set of persist operations, if any of them fails, i must perform a rollback, so i found JTA can do the job but using this piece of source code:

@Stateless
public class ProjectBean implements IProject {

@Resource
javax.transaction.UserTransaction utx;
@PersistenceContext(unitName = "JPADB")
private EntityManager entityManager;
  ...
 //more code

//this is part of a method
try{
utx.begin();
entityManager.joinTransaction();
    for(Project p:projectResultList){
                entityManager.persist(p);
            }
            utx.commit();
        }catch(Exception e){
            e.printStackTrace();
            if(utx != null)
                try {
                    utx.rollback();
                } catch (IllegalStateException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (SecurityException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (SystemException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                //tx.rollback();
        }

simply doesn't work, and this is how the persistence.xml looks like:

<persistence-unit name="JPADB">
<jta-data-source>java:jboss/datasources/OracleBic</jta-data-source>
    <properties>
        <property name="hibernate.show_sql" value ="true" />
        <property name="hibernate.dialect"  value="org.hibernate.dialect.Oracle10gDialect" />
    </properties>
</persistence-unit>

really hope anyone can give me a tip or advice, i'm a newbie with jpa/jta concepts and i tried lots of codes i found in the web but i always obtain different errors (Wrong tx on thread: expected TransactionImple usertransaction begin,Cannot use an EntityTransaction while using JTA). thanks in advance.


Solution

  • Did you instruct your AS that you are going to handle transactions manually with @TransactionManagement(TransactionManagementType.BEAN) on method level? I do not see the annotation on class level. Probably you have it on method level, but your code snipped is insufficient to make any guess. Otherwise all transactions are Container managed and your code is not going to work. So you have to either put @TransactionManagement(TransactionManagementType.BEAN) on either a method or class level depends on requirements or you may want to allow your container to manage transactions for you and than you have to make changes that @remigio suggested to you. It seems that the second approach is better in your case