class JPACategory{
// Let's enhance JPA EntityManager without getting into the JSR committee
static void persistAll( EntityManager em , List entities ){ //add an interface to save all
entities.each{ em.persist(it) }
}
}
def transactionContext = { EntityManager em, Closure c ->
def tx = em.transaction
try{
tx.begin();
use(JPACategory){
c();
}
tx.commit();
}catch(e){
tx.rollback();
}finally{
//cleanup your resource here
}
}
// user code, they always forget to close resource in exception, some even forget to commit, let's not rely on them.
EntityManager em; //probably injected
transactionContext(em){
em.persistAll( [obj1, obj2, obj3] );
// let's do some logics here to make the example sensible
em.persistAll( [obj2, obj4, obj6] );
}
|