springhibernatespring-mvcspring-transactionsnative-sql

How to manage 2 DAO methods in a single transaction?


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.


Solution

  • 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.