public interface UnitOfWork
We provide an UnitOfWork to simplify the amount of code required to interact within the
database.
For example the next line:
{
require(UnitOfWork.class).apply(em -> {
return em.createQuery("from Beer").getResultList();
});
}
Is the same as:
{
Session session = require(SessionFactory.class).openSession();
Transaction trx = session.getTransaction();
try {
trx.begin();
List<Beer> beers = em.createQuery("from Beer").getResultList();
trx.commit();
} catch (Exception ex) {
trx.rollback();
} finally {
session.close();
}
}
An UnitOfWork takes care of transactions and session life-cycle. It's worth to mention
too that a first requested UnitOfWork bind the Session to the current request. If later
in the execution flow an UnitOfWork, Session and/or EntityManager is
required then the one that belong to the current request (first requested) will be provided it.
| Modifier and Type | Method and Description |
|---|---|
default void |
accept(org.jooby.funzy.Throwing.Consumer<org.hibernate.Session> callback)
Get access to a
Session/EntityManager and do some work. |
<T> T |
apply(org.jooby.funzy.Throwing.Function<org.hibernate.Session,T> callback)
Get access to a
Session/EntityManager, do some work and returns some value. |
default void accept(org.jooby.funzy.Throwing.Consumer<org.hibernate.Session> callback)
throws Throwable
Session/EntityManager and do some work.callback - Callback to run.Throwable - If something goes wrong.<T> T apply(org.jooby.funzy.Throwing.Function<org.hibernate.Session,T> callback)
throws Throwable
Session/EntityManager, do some work and returns some value.T - Return type.callback - Callback to run.Throwable - If something goes wrong.Copyright © 2019. All rights reserved.