0

I need to manage 2 Dao methods in a single transaction ,failure of either of them should rollback the other. The calling method is in the service layer. The technology used in Spring and Hibernate native sql query. Is there a way to achieve this?
Calling Method:: @Transactional(propagation= Propagation.REQUIRED) public String save(AllowFileTypesForm formBeanObj,Hashtable global)

Called Method1::

public  boolean deleteData( String strTableName,String strWhereClause)  {
      Session session = sessionFactory.getCurrentSession();                                  
      String strSqlQuery = null;
      boolean deleted=false;
      strSqlQuery = "DELETE FROM Persons where" + strWhereClause;
      try {
           Query query=session.createSQLQuery(strSqlQuery);  
            if (query.executeUpdate() <= 0) {
              throw new SQLException("No row deleted from table "      +strTableName);
        }
          else{
            deleted=true;
        }
    } 

          catch(Exception e){
          e.printStackTrace();
      }
      return deleted;
   }

Similar to this method there is another method which deletes data from some other table.

Shivayan
  • 136
  • 1
  • 2
  • 13
  • Yes. Make your service method transactional. That's the typical way of doing. Why isn't your service layer transactional already? Where is your code? – JB Nizet May 07 '15 at 10:36
  • My Service layer is already transactional but the issue i found is that the rollback isn't taking place and what i believe the reason is @Transactional supports entity persistence and not row insertion. I have posted the codes. – Shivayan May 07 '15 at 10:46
  • What do you mean by "failure" exactly? Because the above code catches all the exceptions that can possibly happen and ignore them, thus effectively preventing the transaction to rollback in case an exception is thrown. – JB Nizet May 07 '15 at 11:34

2 Answers2

2

It will not rollback because you are catching the exceptions. Spring's transaction management works through exceptions exiting the transaction boundary which are detected by the @Transactional AOP.

If you catch a sql exception for logging or something you must rethrow or throw a new exception to kick off rollback.

Adam Gent
  • 47,843
  • 23
  • 153
  • 203
1

Add @Transactional on the service method from where you are calling those DAO methods. This article nicely sums up how it works.

mushfek0001
  • 3,845
  • 1
  • 21
  • 20