Last active
December 29, 2015 16:09
-
-
Save jweyrich/7695517 to your computer and use it in GitHub Desktop.
Quick and ugly support for transactional tasks using vraptor-tasks and Hibernate.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is really awesome.
In any post I could find something so usefull to Vraptor-Task as it!