2014-10-10 2 views
0

Я обрабатываю три транзакции внутри одного метода в управляемом bean-компоненте без состояния. I хочу сохранить три транзакции, а если один из них вызывает исключение, другие два должны завершить свою соответствующую транзакцию, ошибка в том, что, если первый или какой-либо один бросает исключение два других к выполнению просьба дать некоторые полезные внушенияСбой транзакции EJB3.0 внутри метода при последовательных транзакциях.

public void allocateSubjectToStudent(SubjectAllocatedToStudentDto dto)throws Exception { 
      logger.info("allocateSubjectToStudent method entry :"); 


       List<Subject> coreList=dto.getCoreList(); 
       Iterator<Subject> iterator=coreList.iterator(); 
       while(iterator.hasNext()){ 
        logger.info("inside while :"); 
        SubjectAllocatedToStudentBo bo=new SubjectAllocatedToStudentBo(); 
        bo.setBacthId(dto.getBacthId()); 
        bo.setSemester(dto.getSemester()); 
        bo.setStudentId(dto.getStudentId()); 
        Subject subject=iterator.next(); 
        bo.setSubjectName(subject.getSubjectName()); 
        bo.setSubjectType(subject.getAbbreviation()); 

        try{ 
         manager.persist(bo); 
        } 
        catch(javax.persistence.PersistenceException e){ 
         Throwable t = e.getCause(); 
         while ((t != null) && !(t instanceof org.hibernate.exception.ConstraintViolationException)) { 
          t = t.getCause(); 
         }//while 
         if (t instanceof org.hibernate.exception.ConstraintViolationException) { 
          throw new Exception("Core subject already allocated to student"); 
         } //end of if 
        }//end of catch 
       }//end of while 

       List<Subject> departmentallist=dto.getDepartmentList(); 
       Iterator<Subject> iterator1=departmentallist.iterator(); 
       while(iterator1.hasNext()){ 

        logger.info("inside while :"); 
        SubjectAllocatedToStudentBo bo=new SubjectAllocatedToStudentBo(); 
        bo.setBacthId(dto.getBacthId()); 
        bo.setSemester(dto.getSemester()); 
        bo.setStudentId(dto.getStudentId()); 
        Subject subject=iterator1.next(); 
        bo.setSubjectName(subject.getSubjectName()); 
        bo.setSubjectType(subject.getAbbreviation()); 
        try{ 
         manager.persist(bo); 
         } 
         catch(javax.persistence.PersistenceException e){ 

          Throwable t = e.getCause(); 
          while ((t != null) && !(t instanceof org.hibernate.exception.ConstraintViolationException)) { 
           t = t.getCause(); 
          }//while 
          if (t instanceof org.hibernate.exception.ConstraintViolationException) { 
           throw new Exception("InterDepartmental subject already allocated to student"); 
          } //end of if 
         }//end of catch 
       }//end of while 

       List<Subject> electiveList=dto.getElectiveList(); 
       Iterator<Subject> iterator2=electiveList.iterator(); 
       while(iterator2.hasNext()){ 

        logger.info("inside while :"); 
        SubjectAllocatedToStudentBo bo=new SubjectAllocatedToStudentBo(); 
        bo.setBacthId(dto.getBacthId()); 
        bo.setSemester(dto.getSemester()); 
        bo.setStudentId(dto.getStudentId()); 
        Subject subject=iterator2.next(); 
        bo.setSubjectName(subject.getSubjectName()); 
        bo.setSubjectType(subject.getAbbreviation()); 
        try{ 
         manager.persist(bo); 
         } 
         catch(javax.persistence.PersistenceException e){ 

          Throwable t = e.getCause(); 
          while ((t != null) && !(t instanceof org.hibernate.exception.ConstraintViolationException)) { 
           t = t.getCause(); 
          }//while 
          if (t instanceof org.hibernate.exception.ConstraintViolationException) { 
           throw new Exception("Elective subject already allocated to student"); 
          } //end of if 
         }//end of catch 
       }//end of while 


      logger.info("allocateSubjectToStudent method exit :"); 

     } //end of method 

ответ

1

в рамках одного вызова метода есть только одна транзакция активна. Чтобы достичь того, чего вы хотите, вы должны выполнить три операции в разных транзакциях. Для этого потребуется еще один уровень абстракции.

public class MyFreshTransaction { 

    @TransactionAttribute(REQUIRES_NEW) 
    public void updateO() { 
    //do something 
    } 

    @TransactionAttribute(REQUIRES_NEW) 
    public void update1() { 
    //do something 
    } 

    @TransactionAttribute(REQUIRES_NEW) 
    public void update2() { 
    //do something 
    } 
} 

@Stateless 
public class MyTransactionProcessor { 

    @EJB 
    private MyFreshTransaction freshTransaction; 

    public void processTransaction() { 
    try { 
     //The current transaction context will be suspended, and a new one invoked 
     //if the new one fails and is rollback, the current one is not affected. 
     //you can then handle the exception, by rethrowing the exception,in which case 
     //the current transaction will also be rolled back, or continue based on your logic. 
     freshTransaction.update0(); 
    } catch (Exception ex) {//handle} 

    try { 
     //The current transaction context will be suspended, and a new one invoked 
     //if the new one fails and is rollback, the current one is not affected. 
     //you can then handle the exception, by rethrowing the exception,in which case 
     //the current transaction will also be rolled back, or continue based on your logic. 
     freshTransaction.update1(); 
    } catch (Exception ex) {//handle} 

    try { 
     //The current transaction context will be suspended, and a new one invoked 
     //if the new one fails and is rollback, the current one is not affected. 
     //you can then handle the exception, by rethrowing the exception,in which case 
     //the current transaction will also be rolled back, or continue based on your logic. 
     freshTransaction.update2(); 
    } catch (Exception ex) {//handle} 
    } 
} 

Обратите внимание, что если какой-либо сделки обновление было успешным, и родительский откат транзакции, это не повлияет на статус сделок «ребенок», так как они уже были совершены, и их последствия (если эффекты БД) также будут совершены.

чтения на Java EE Операции Java EE Transactions

+0

Я не хочу, чтобы создать другой класс. я попытался сделать это, создав внутренний класс, но не работая – Shardendu

+0

Единственный способ, которым EJB сможет управлять транзакцией, - это управлять вашими бобами. Вы также можете ввести компонент в себя (я не тестировал это, но думаю, он должен работать) – maress

1

создать три различных метода все с TranscationAttributeType REQUIRES_NEW Вы найдете ниже фрагмент кода для EJB3 Bean

public void doYourWork() 
{ 
    a(); 
    b(); 
    c(); 

} 
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) 
public void a() 
{ 
    try 
    { 
     //Do the first transaction here 
    }catch(Exception e) 
    { 

    } 
} 

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) 
public void b() 
{ 
    try 
    { 
     //Do the second transaction here 
    }catch(Exception e) 
    { 

    } 
} 

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) 
public void c() 
{ 
    try 
    { 
     //Do the third transaction here 
    }catch(Exception e) 
    { 

    } 
} 
+0

Я создал три метода, но он вообще не работает. Вы можете показать мне свой код, как вы хотите, чтобы я его реализовал? – Shardendu

+0

внутри catch я бросаю исключение, я думаю, из-за чего другие две транзакции не выполняются. Я хочу бросить различное сообщение на разные уловки. – Shardendu

+0

Если вы используете REUIRES_NEW, тогда другие две транзакции не будут нарушены. –

Смежные вопросы