public interface UnitOfWork
EntityManager.
According to JPA every thread should use its own EntityManager. Therefore the unit of
work will control the life cycle of the EntityManager on a per thread basis. This means
the UnitOfWork is thread safe.
Most of the time it is not recommended to manual control the unit of work.
For applications running in a container the PersistenceFilter is recommended.
It will start a unit of work for every incoming request and properly close it at the end.
For stand alone application it is recommended to relay on the @Transactional annotation.
The transaction handler will automatically span a unit of work around a transaction.
The most likely scenario in which one would want to take manual control over the unit of work
is in a background thread within a container (i.e. timer triggered jobs).
Recommended pattern:
public void someMethod() {
final boolean unitOfWorkWasInactive = ! unitOfWork.isActive();
if (unitOfWorkWasInactive) {
unitOfWork.begin();
}
try {
// do work
}
finally {
if (unitOfWorkWasInactive) {
unitOfWork.end();
}
}
}
void begin()
IllegalStateException is thrown.IllegalStateException - if a unit of work is already active for this thread.boolean isActive()
true if the unit of work is active for the current thread
false otherwise.void end()
Copyright © 2013–2014 The Apache Software Foundation. All rights reserved.