Skip to content

Instantly share code, notes, and snippets.

@jweyrich
Last active December 29, 2015 16:09
Show Gist options
  • Save jweyrich/7695517 to your computer and use it in GitHub Desktop.
Save jweyrich/7695517 to your computer and use it in GitHub Desktop.
Quick and ugly support for transactional tasks using vraptor-tasks and Hibernate.
package ...;
import br.com.caelum.vraptor.tasks.Task;
import javax.inject.Inject;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jardel Weyrich
*/
public abstract class TransactionalTask implements Task {
private static final Logger log = LoggerFactory.getLogger(TransactionalTask.class);
@Inject protected SessionFactory sessionFactory;
protected Session session;
@Override
public void execute() {
final boolean canContinue = beforeExecute();
if (!canContinue)
return;
try {
session.beginTransaction();
doWork();
session.flush();
session.getTransaction().commit();
} catch (HibernateException e) {
session.getTransaction().rollback();
throw e; // or display error message
}
afterExecute();
}
protected boolean beforeExecute() {
this.session = this.sessionFactory.openSession();
if (this.session == null) {
log.error("Could not get an instance of {0}", Session.class.getCanonicalName());
return false; // FIXME: Should throw an exception and abort execution?
}
return true;
}
protected void afterExecute() {
if (this.session != null && this.session.isOpen())
this.session.close();
}
public abstract void doWork();
}
@robertoalvesme
Copy link

This is really awesome.
In any post I could find something so usefull to Vraptor-Task as it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment