I just realized that the suggested Spring Transaction Entity Provider from the JPAContainer manual includes notifying listeners within the transaction, and it’s also very much copy-paste when a new entity should be handled. I wrote up a suggestion for a new class with the same purpose. I’d be happy to receive feedback on it.
public abstract class TransactionalEntityProvider<T> extends MutableLocalEntityProvider<T> {
@PersistenceContext
private EntityManager em;
public TransactionalEntityProvider(Class<T> entityClass) {
super(entityClass);
setTransactionsHandledByProvider(false);
}
@PostConstruct
public void init() {
setEntityManager(em);
/*
* The entity manager is transaction scoped, which means that the entities will be automatically detached when the transaction is
* closed. Therefore, we do not need to explicitly detach them.
*/
setEntitiesDetached(false);
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
protected void runInTransaction(Runnable operation) {
super.runInTransaction(operation);
}
@Override
public T updateEntity(final T entity) {
return super.updateEntity(entity);
}
@Override
public T addEntity(final T entity) {
return super.addEntity(entity);
}
@Override
public void removeEntity(final Object entityId) {
super.removeEntity(entityId);
}
@Override
public void updateEntityProperty(final Object entityId, final String propertyName, final Object propertyValue)
throws IllegalArgumentException {
super.updateEntityProperty(entityId, propertyName, propertyValue);
}
}
And an implementation would look like
@Repository
public class BoatEntityProvider extends TransactionalEntityProvider<Boat> {
protected BoatEntityProvider() {
super(Boat.class);
}
}