Java Code Examples for org.springframework.transaction.support.TransactionSynchronizationManager#hasResource()

The following examples show how to use org.springframework.transaction.support.TransactionSynchronizationManager#hasResource() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JcrInterceptor.java    From mycollab with GNU Affero General Public License v3.0 6 votes vote down vote up
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    boolean existingTransaction = false;
    Session session = SessionFactoryUtils.getSession(getSessionFactory(), true);
    if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
        LOG.debug("Found thread-bound Session for JCR interceptor");
        existingTransaction = true;
    } else {
        LOG.debug("Using new Session for JCR interceptor");
        TransactionSynchronizationManager.bindResource(getSessionFactory(), getSessionFactory().getSessionHolder(session));
    }
    try {
        Object retVal = methodInvocation.proceed();
        // flushIfNecessary(session, existingTransaction);
        return retVal;
    } finally {
        if (existingTransaction) {
            LOG.debug("Not closing pre-bound JCR Session after interceptor");
        } else {
            TransactionSynchronizationManager.unbindResource(getSessionFactory());
            SessionFactoryUtils.releaseSession(session, getSessionFactory());
        }
    }
}
 
Example 2
Source File: OpenSessionInterceptor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	SessionFactory sf = getSessionFactory();
	if (!TransactionSynchronizationManager.hasResource(sf)) {
		// New Session to be bound for the current method's scope...
		Session session = openSession();
		try {
			TransactionSynchronizationManager.bindResource(sf, new org.springframework.orm.hibernate3.SessionHolder(session));
			return invocation.proceed();
		}
		finally {
			org.springframework.orm.hibernate3.SessionFactoryUtils.closeSession(session);
			TransactionSynchronizationManager.unbindResource(sf);
		}
	}
	else {
		// Pre-bound Session found -> simply proceed.
		return invocation.proceed();
	}
}
 
Example 3
Source File: OpenSessionInterceptor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	SessionFactory sf = getSessionFactory();
	if (!TransactionSynchronizationManager.hasResource(sf)) {
		// New Session to be bound for the current method's scope...
		Session session = openSession();
		try {
			TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
			return invocation.proceed();
		}
		finally {
			SessionFactoryUtils.closeSession(session);
			TransactionSynchronizationManager.unbindResource(sf);
		}
	}
	else {
		// Pre-bound Session found -> simply proceed.
		return invocation.proceed();
	}
}
 
Example 4
Source File: HibernatePersistenceContextInterceptor.java    From gorm-hibernate5 with Apache License 2.0 6 votes vote down vote up
public void init() {
    if (incNestingCount() > 1) {
        return;
    }
    SessionFactory sf = getSessionFactory();
    if (sf == null) {
        return;
    }
    if (TransactionSynchronizationManager.hasResource(sf)) {
        // Do not modify the Session: just set the participate flag.
        setParticipate(true);
    }
    else {
        setParticipate(false);
        LOG.debug("Opening single Hibernate session in HibernatePersistenceContextInterceptor");
        Session session = getSession();
        HibernateRuntimeUtils.enableDynamicFilterEnablerIfPresent(sf, session);
        TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
    }
}
 
Example 5
Source File: OpenPersistenceManagerInViewInterceptor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	if (TransactionSynchronizationManager.hasResource(getPersistenceManagerFactory())) {
		// Do not modify the PersistenceManager: just mark the request accordingly.
		String participateAttributeName = getParticipateAttributeName();
		Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening JDO PersistenceManager in OpenPersistenceManagerInViewInterceptor");
		PersistenceManager pm =
				PersistenceManagerFactoryUtils.getPersistenceManager(getPersistenceManagerFactory(), true);
		TransactionSynchronizationManager.bindResource(
				getPersistenceManagerFactory(), new PersistenceManagerHolder(pm));
	}
}
 
Example 6
Source File: OpenPersistenceManagerInViewInterceptor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	if (TransactionSynchronizationManager.hasResource(getPersistenceManagerFactory())) {
		// Do not modify the PersistenceManager: just mark the request accordingly.
		String participateAttributeName = getParticipateAttributeName();
		Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening JDO PersistenceManager in OpenPersistenceManagerInViewInterceptor");
		PersistenceManager pm =
				PersistenceManagerFactoryUtils.getPersistenceManager(getPersistenceManagerFactory(), true);
		TransactionSynchronizationManager.bindResource(
				getPersistenceManagerFactory(), new PersistenceManagerHolder(pm));
	}
}
 
Example 7
Source File: OpenEntityManagerInViewInterceptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String key = getParticipateAttributeName();
	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult() && applyEntityManagerBindingInterceptor(asyncManager, key)) {
		return;
	}

	EntityManagerFactory emf = obtainEntityManagerFactory();
	if (TransactionSynchronizationManager.hasResource(emf)) {
		// Do not modify the EntityManager: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewInterceptor");
		try {
			EntityManager em = createEntityManager();
			EntityManagerHolder emHolder = new EntityManagerHolder(em);
			TransactionSynchronizationManager.bindResource(emf, emHolder);

			AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(emf, emHolder);
			asyncManager.registerCallableInterceptor(key, interceptor);
			asyncManager.registerDeferredResultInterceptor(key, interceptor);
		}
		catch (PersistenceException ex) {
			throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
		}
	}
}
 
Example 8
Source File: ExtendedEntityManagerCreator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Join an existing transaction, if not already joined.
 * @param enforce whether to enforce the transaction
 * (i.e. whether failure to join is considered fatal)
 */
private void doJoinTransaction(boolean enforce) {
	if (this.jta) {
		// Let's try whether we're in a JTA transaction.
		try {
			this.target.joinTransaction();
			logger.debug("Joined JTA transaction");
		}
		catch (TransactionRequiredException ex) {
			if (!enforce) {
				logger.debug("No JTA transaction to join: " + ex);
			}
			else {
				throw ex;
			}
		}
	}
	else {
		if (TransactionSynchronizationManager.isSynchronizationActive()) {
			if (!TransactionSynchronizationManager.hasResource(this.target) &&
					!this.target.getTransaction().isActive()) {
				enlistInCurrentTransaction();
			}
			logger.debug("Joined local transaction");
		}
		else {
			if (!enforce) {
				logger.debug("No local transaction to join");
			}
			else {
				throw new TransactionRequiredException("No local transaction to join");
			}
		}
	}
}
 
Example 9
Source File: OpenPersistenceManagerInViewFilter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(
		HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {

	PersistenceManagerFactory pmf = lookupPersistenceManagerFactory(request);
	boolean participate = false;

	if (TransactionSynchronizationManager.hasResource(pmf)) {
		// Do not modify the PersistenceManager: just set the participate flag.
		participate = true;
	}
	else {
		logger.debug("Opening JDO PersistenceManager in OpenPersistenceManagerInViewFilter");
		PersistenceManager pm = PersistenceManagerFactoryUtils.getPersistenceManager(pmf, true);
		TransactionSynchronizationManager.bindResource(pmf, new PersistenceManagerHolder(pm));
	}

	try {
		filterChain.doFilter(request, response);
	}

	finally {
		if (!participate) {
			PersistenceManagerHolder pmHolder = (PersistenceManagerHolder)
					TransactionSynchronizationManager.unbindResource(pmf);
			logger.debug("Closing JDO PersistenceManager in OpenPersistenceManagerInViewFilter");
			PersistenceManagerFactoryUtils.releasePersistenceManager(pmHolder.getPersistenceManager(), pmf);
		}
	}
}
 
Example 10
Source File: HibernateTransactionManager.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected void doResume(Object transaction, Object suspendedResources) {
	SuspendedResourcesHolder resourcesHolder = (SuspendedResourcesHolder) suspendedResources;
	if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
		// From non-transactional code running in active transaction synchronization
		// -> can be safely removed, will be closed on transaction completion.
		TransactionSynchronizationManager.unbindResource(getSessionFactory());
	}
	TransactionSynchronizationManager.bindResource(getSessionFactory(), resourcesHolder.getSessionHolder());
	if (getDataSource() != null) {
		TransactionSynchronizationManager.bindResource(getDataSource(), resourcesHolder.getConnectionHolder());
	}
}
 
Example 11
Source File: OpenSessionInViewInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Open a new Hibernate {@code Session} according and bind it to the thread via the
 * {@link TransactionSynchronizationManager}.
 */
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String key = getParticipateAttributeName();
	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult() && applySessionBindingInterceptor(asyncManager, key)) {
		return;
	}

	if (TransactionSynchronizationManager.hasResource(obtainSessionFactory())) {
		// Do not modify the Session: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
		Session session = openSession();
		SessionHolder sessionHolder = new SessionHolder(session);
		TransactionSynchronizationManager.bindResource(obtainSessionFactory(), sessionHolder);

		AsyncRequestInterceptor asyncRequestInterceptor =
				new AsyncRequestInterceptor(obtainSessionFactory(), sessionHolder);
		asyncManager.registerCallableInterceptor(key, asyncRequestInterceptor);
		asyncManager.registerDeferredResultInterceptor(key, asyncRequestInterceptor);
	}
}
 
Example 12
Source File: OpenEntityManagerInViewInterceptor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String participateAttributeName = getParticipateAttributeName();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult()) {
		if (applyCallableInterceptor(asyncManager, participateAttributeName)) {
			return;
		}
	}

	if (TransactionSynchronizationManager.hasResource(getEntityManagerFactory())) {
		// Do not modify the EntityManager: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewInterceptor");
		try {
			EntityManager em = createEntityManager();
			EntityManagerHolder emHolder = new EntityManagerHolder(em);
			TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), emHolder);

			AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(getEntityManagerFactory(), emHolder);
			asyncManager.registerCallableInterceptor(participateAttributeName, interceptor);
			asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor);
		}
		catch (PersistenceException ex) {
			throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
		}
	}
}
 
Example 13
Source File: OpenSessionInViewInterceptor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Open a new Hibernate {@code Session} according to the settings of this
 * {@code HibernateAccessor} and bind it to the thread via the
 * {@link TransactionSynchronizationManager}.
 * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession
 */
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String participateAttributeName = getParticipateAttributeName();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult()) {
		if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) {
			return;
		}
	}

	if ((isSingleSession() && TransactionSynchronizationManager.hasResource(getSessionFactory())) ||
		SessionFactoryUtils.isDeferredCloseActive(getSessionFactory())) {
		// Do not modify the Session: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		if (isSingleSession()) {
			// single session mode
			logger.debug("Opening single Hibernate Session in OpenSessionInViewInterceptor");
			Session session = SessionFactoryUtils.getSession(
					getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
			applyFlushMode(session, false);
			SessionHolder sessionHolder = new SessionHolder(session);
			TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);

			AsyncRequestInterceptor asyncRequestInterceptor =
					new AsyncRequestInterceptor(getSessionFactory(), sessionHolder);
			asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor);
			asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor);
		}
		else {
			// deferred close mode
			SessionFactoryUtils.initDeferredClose(getSessionFactory());
		}
	}
}
 
Example 14
Source File: OpenEntityManagerInViewInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String key = getParticipateAttributeName();
	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult() && applyEntityManagerBindingInterceptor(asyncManager, key)) {
		return;
	}

	EntityManagerFactory emf = obtainEntityManagerFactory();
	if (TransactionSynchronizationManager.hasResource(emf)) {
		// Do not modify the EntityManager: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewInterceptor");
		try {
			EntityManager em = createEntityManager();
			EntityManagerHolder emHolder = new EntityManagerHolder(em);
			TransactionSynchronizationManager.bindResource(emf, emHolder);

			AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(emf, emHolder);
			asyncManager.registerCallableInterceptor(key, interceptor);
			asyncManager.registerDeferredResultInterceptor(key, interceptor);
		}
		catch (PersistenceException ex) {
			throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
		}
	}
}
 
Example 15
Source File: OpenPersistenceManagerInViewFilter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(
		HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {

	PersistenceManagerFactory pmf = lookupPersistenceManagerFactory(request);
	boolean participate = false;

	if (TransactionSynchronizationManager.hasResource(pmf)) {
		// Do not modify the PersistenceManager: just set the participate flag.
		participate = true;
	}
	else {
		logger.debug("Opening JDO PersistenceManager in OpenPersistenceManagerInViewFilter");
		PersistenceManager pm = PersistenceManagerFactoryUtils.getPersistenceManager(pmf, true);
		TransactionSynchronizationManager.bindResource(pmf, new PersistenceManagerHolder(pm));
	}

	try {
		filterChain.doFilter(request, response);
	}

	finally {
		if (!participate) {
			PersistenceManagerHolder pmHolder = (PersistenceManagerHolder)
					TransactionSynchronizationManager.unbindResource(pmf);
			logger.debug("Closing JDO PersistenceManager in OpenPersistenceManagerInViewFilter");
			PersistenceManagerFactoryUtils.releasePersistenceManager(pmHolder.getPersistenceManager(), pmf);
		}
	}
}
 
Example 16
Source File: OpenSessionInViewInterceptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Open a new Hibernate {@code Session} according and bind it to the thread via the
 * {@link TransactionSynchronizationManager}.
 */
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String key = getParticipateAttributeName();
	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult() && applySessionBindingInterceptor(asyncManager, key)) {
		return;
	}

	if (TransactionSynchronizationManager.hasResource(obtainSessionFactory())) {
		// Do not modify the Session: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
		Session session = openSession();
		SessionHolder sessionHolder = new SessionHolder(session);
		TransactionSynchronizationManager.bindResource(obtainSessionFactory(), sessionHolder);

		AsyncRequestInterceptor asyncRequestInterceptor =
				new AsyncRequestInterceptor(obtainSessionFactory(), sessionHolder);
		asyncManager.registerCallableInterceptor(key, asyncRequestInterceptor);
		asyncManager.registerDeferredResultInterceptor(key, asyncRequestInterceptor);
	}
}
 
Example 17
Source File: OpenSessionInViewInterceptor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Open a new Hibernate {@code Session} according and bind it to the thread via the
 * {@link TransactionSynchronizationManager}.
 */
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String participateAttributeName = getParticipateAttributeName();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult()) {
		if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) {
			return;
		}
	}

	if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
		// Do not modify the Session: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
		Session session = openSession();
		SessionHolder sessionHolder = new SessionHolder(session);
		TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);

		AsyncRequestInterceptor asyncRequestInterceptor =
				new AsyncRequestInterceptor(getSessionFactory(), sessionHolder);
		asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor);
		asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor);
	}
}
 
Example 18
Source File: OpenSessionInViewInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open a new Hibernate {@code Session} according and bind it to the thread via the
 * {@link org.springframework.transaction.support.TransactionSynchronizationManager}.
 */
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String participateAttributeName = getParticipateAttributeName();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult()) {
		if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) {
			return;
		}
	}

	if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
		// Do not modify the Session: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
		Session session = openSession();
		SessionHolder sessionHolder = new SessionHolder(session);
		TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);

		AsyncRequestInterceptor asyncRequestInterceptor =
				new AsyncRequestInterceptor(getSessionFactory(), sessionHolder);
		asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor);
		asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor);
	}
}
 
Example 19
Source File: ExtendedEntityManagerCreator.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
@Nullable
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	// Invocation on EntityManager interface coming in...

	if (method.getName().equals("equals")) {
		// Only consider equal when proxies are identical.
		return (proxy == args[0]);
	}
	else if (method.getName().equals("hashCode")) {
		// Use hashCode of EntityManager proxy.
		return hashCode();
	}
	else if (method.getName().equals("getTargetEntityManager")) {
		// Handle EntityManagerProxy interface.
		return this.target;
	}
	else if (method.getName().equals("unwrap")) {
		// Handle JPA 2.0 unwrap method - could be a proxy match.
		Class<?> targetClass = (Class<?>) args[0];
		if (targetClass == null) {
			return this.target;
		}
		else if (targetClass.isInstance(proxy)) {
			return proxy;
		}
	}
	else if (method.getName().equals("isOpen")) {
		if (this.containerManaged) {
			return true;
		}
	}
	else if (method.getName().equals("close")) {
		if (this.containerManaged) {
			throw new IllegalStateException("Invalid usage: Cannot close a container-managed EntityManager");
		}
		ExtendedEntityManagerSynchronization synch = (ExtendedEntityManagerSynchronization)
				TransactionSynchronizationManager.getResource(this.target);
		if (synch != null) {
			// Local transaction joined - don't actually call close() before transaction completion
			synch.closeOnCompletion = true;
			return null;
		}
	}
	else if (method.getName().equals("getTransaction")) {
		if (this.synchronizedWithTransaction) {
			throw new IllegalStateException(
					"Cannot obtain local EntityTransaction from a transaction-synchronized EntityManager");
		}
	}
	else if (method.getName().equals("joinTransaction")) {
		doJoinTransaction(true);
		return null;
	}
	else if (method.getName().equals("isJoinedToTransaction")) {
		// Handle JPA 2.1 isJoinedToTransaction method for the non-JTA case.
		if (!this.jta) {
			return TransactionSynchronizationManager.hasResource(this.target);
		}
	}

	// Do automatic joining if required. Excludes toString, equals, hashCode calls.
	if (this.synchronizedWithTransaction && method.getDeclaringClass().isInterface()) {
		doJoinTransaction(false);
	}

	// Invoke method on current EntityManager.
	try {
		return method.invoke(this.target, args);
	}
	catch (InvocationTargetException ex) {
		throw ex.getTargetException();
	}
}
 
Example 20
Source File: ExtendedEntityManagerCreator.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
@Nullable
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	// Invocation on EntityManager interface coming in...

	if (method.getName().equals("equals")) {
		// Only consider equal when proxies are identical.
		return (proxy == args[0]);
	}
	else if (method.getName().equals("hashCode")) {
		// Use hashCode of EntityManager proxy.
		return hashCode();
	}
	else if (method.getName().equals("getTargetEntityManager")) {
		// Handle EntityManagerProxy interface.
		return this.target;
	}
	else if (method.getName().equals("unwrap")) {
		// Handle JPA 2.0 unwrap method - could be a proxy match.
		Class<?> targetClass = (Class<?>) args[0];
		if (targetClass == null) {
			return this.target;
		}
		else if (targetClass.isInstance(proxy)) {
			return proxy;
		}
	}
	else if (method.getName().equals("isOpen")) {
		if (this.containerManaged) {
			return true;
		}
	}
	else if (method.getName().equals("close")) {
		if (this.containerManaged) {
			throw new IllegalStateException("Invalid usage: Cannot close a container-managed EntityManager");
		}
		ExtendedEntityManagerSynchronization synch = (ExtendedEntityManagerSynchronization)
				TransactionSynchronizationManager.getResource(this.target);
		if (synch != null) {
			// Local transaction joined - don't actually call close() before transaction completion
			synch.closeOnCompletion = true;
			return null;
		}
	}
	else if (method.getName().equals("getTransaction")) {
		if (this.synchronizedWithTransaction) {
			throw new IllegalStateException(
					"Cannot obtain local EntityTransaction from a transaction-synchronized EntityManager");
		}
	}
	else if (method.getName().equals("joinTransaction")) {
		doJoinTransaction(true);
		return null;
	}
	else if (method.getName().equals("isJoinedToTransaction")) {
		// Handle JPA 2.1 isJoinedToTransaction method for the non-JTA case.
		if (!this.jta) {
			return TransactionSynchronizationManager.hasResource(this.target);
		}
	}

	// Do automatic joining if required. Excludes toString, equals, hashCode calls.
	if (this.synchronizedWithTransaction && method.getDeclaringClass().isInterface()) {
		doJoinTransaction(false);
	}

	// Invoke method on current EntityManager.
	try {
		return method.invoke(this.target, args);
	}
	catch (InvocationTargetException ex) {
		throw ex.getTargetException();
	}
}