Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
titleBGColor#D0D9BD
borderStylesolid
titleClosure, Category and JPA example
borderColor#D0D9BD
borderWidth1
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] );
}