protected final EntityManager getRealEntityManager()

in tx-control-providers/jpa/tx-control-provider-jpa-local/src/main/java/org/apache/aries/tx/control/jpa/local/impl/TxContextBindingJDBCDelegatingEntityManager.java [51:110]


	protected final EntityManager getRealEntityManager() {

		TransactionContext txContext = txControl.getCurrentContext();

		if (txContext == null) {
			throw new TransactionException("The resource " + provider
					+ " cannot be accessed outside of an active Transaction Context");
		}

		EntityManager existing = (EntityManager) txContext.getScopedValue(resourceId);

		if (existing != null) {
			return existing;
		}

		EntityManager toReturn;
		EntityManager toClose;

		try {
			if (txContext.getTransactionStatus() == NO_TRANSACTION) {
				toClose = provider.createEntityManager();
				toReturn = new ScopedEntityManagerWrapper(toClose);
			} else {
				toClose = provider.createEntityManager();
				toReturn = new TxEntityManagerWrapper(toClose);
				
				txContext.preCompletion(toClose::flush);
				toClose.getTransaction().begin();
			}
		} catch (Exception sqle) {
			throw new TransactionException(
					"There was a problem getting hold of a database connection",
					sqle);
		}
		
		txContext.postCompletion(s -> {
				try {
					// Make sure that the transaction ends,
					// and that the EntityManager gets the
					// right cache invalidation based on
					// commit/rollback
					if(s == ROLLED_BACK) {
						toClose.getTransaction().rollback();
					} else {
						toClose.getTransaction().commit();
					}
				} catch (PersistenceException sqle) {
					// TODO log this
				}
				try {
					toClose.close();
				} catch (PersistenceException sqle) {
					// TODO log this
				}
			});
		
		txContext.putScopedValue(resourceId, toReturn);
		
		return toReturn;
	}