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 ?