0

I am using Spring MVC + Hibernate , the following is generic method for save ( one - to Many). I use this to insert the record for both table with the same session, if any one table fail, then all operation roll beck because they are associate with same session

public <T, E> long save(T entity, List<E> list) throws DataAccessException {

    Session session = sessionFactory.getCurrentSession();
    long getGenVal=(Long)session.save(entity);
    for(E getlist : list){
    session.save(getlist);
    }

    return getGenVal;
}

In Controller

@Resource(name = "PersistenceTemplate")
private PersistenceTemplate pt;
long getGenVal=pt.save(purchaseReq,list);

Now I want to maintain audit log, for this purpose I add another argument in same method (save)to associate this operation with same session, so that if any table of 3 tables, create problem. Then transaction rollback automatically. ( spring feature)

public <T, E, K> long save(T entity, List<E> list, K audit) throws DataAccessException {

        Session session = sessionFactory.getCurrentSession();
        long getGenVal=(Long)session.save(entity);
        for(E getlist : list){
        session.save(getlist);
        }
        session.save(audit);
        return getGenVal;
    }

so All three operation associate with same session

But Not I have a problem , because Audit Trail (log) entity required Id of newly insert Record such as ( In Controller )

purchaseReqAT= new ProPurchReqATModel("NEW REQUISION", "INSERT", 1, userId, userIp, sysdate);

["INSERT", 1, userId] 1 between INSERT and userId is ID (PK) that is newly generated !

If I create a separate method to save the audit trail after getting the id of new inserted record. such as

public <T> long save(T auditTrail) throws DataAccessException {
    Session session = sessionFactory.getCurrentSession();
    long getGenVal=(Long) session.save(auditTrail);
    return getGenVal;
}

and audit trail fails to insert the record in table, how can I roll back all previous transaction ? and how we can associate the new generated ID with audit trial within same method .

any solution ?

Shahid Ghafoor
  • 2,991
  • 17
  • 68
  • 123

1 Answers1

0

You should have a service layer which incorporates this, and the service layer should be the transactional layer. The service should call the different repositories/daos, this way everything happens in a single transaction.

It also simplifies your controller code (that should merely be a thin layer between your web request and the calling of a service method it should not contain business logic).

However for writing an audit record I would write a hibernate interceptor, that way writing your audit records is transparent and you don't forget to include it in the data modification records.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224