protected final EntityManager getRealEntityManager()

in tx-control-providers/jpa/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/XATxContextBindingEntityManager.java [54:107]


	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;
		}

		TransactionControl previous = commonTxStore.get();
		commonTxStore.set(txControl);
		
		EntityManager toReturn;
		EntityManager toClose;

		try {
			if (txContext.getTransactionStatus() == NO_TRANSACTION) {
				toClose = provider.createEntityManager();
				toReturn = new ScopedEntityManagerWrapper(toClose);
			} else if (txContext.supportsXA()) {
				toClose = provider.createEntityManager();
				toReturn = new TxEntityManagerWrapper(toClose);
				toClose.joinTransaction();
			} else {
				throw new TransactionException(
						"There is a transaction active, but it does not support xa participants");
			}
		} catch (Exception sqle) {
			commonTxStore.set(previous);
			throw new TransactionException(
					"There was a problem getting hold of a database connection",
					sqle);
		}

		
		txContext.postCompletion(x -> {
				try {
					toClose.close();
				} catch (PersistenceException sqle) {
					// TODO log this
				}
				commonTxStore.set(previous);
			});
		
		txContext.putScopedValue(resourceId, toReturn);
		
		return toReturn;
	}