001/* 002 * Copyright 2002-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.orm.jpa; 018 019import javax.persistence.EntityManager; 020 021import org.springframework.lang.Nullable; 022import org.springframework.transaction.SavepointManager; 023import org.springframework.transaction.support.ResourceHolderSupport; 024import org.springframework.util.Assert; 025 026/** 027 * Resource holder wrapping a JPA {@link EntityManager}. 028 * {@link JpaTransactionManager} binds instances of this class to the thread, 029 * for a given {@link javax.persistence.EntityManagerFactory}. 030 * 031 * <p>Also serves as a base class for {@link org.springframework.orm.hibernate5.SessionHolder}, 032 * as of 5.1. 033 * 034 * <p>Note: This is an SPI class, not intended to be used by applications. 035 * 036 * @author Juergen Hoeller 037 * @since 2.0 038 * @see JpaTransactionManager 039 * @see EntityManagerFactoryUtils 040 */ 041public class EntityManagerHolder extends ResourceHolderSupport { 042 043 @Nullable 044 private final EntityManager entityManager; 045 046 private boolean transactionActive; 047 048 @Nullable 049 private SavepointManager savepointManager; 050 051 052 public EntityManagerHolder(@Nullable EntityManager entityManager) { 053 this.entityManager = entityManager; 054 } 055 056 057 public EntityManager getEntityManager() { 058 Assert.state(this.entityManager != null, "No EntityManager available"); 059 return this.entityManager; 060 } 061 062 protected void setTransactionActive(boolean transactionActive) { 063 this.transactionActive = transactionActive; 064 } 065 066 protected boolean isTransactionActive() { 067 return this.transactionActive; 068 } 069 070 protected void setSavepointManager(@Nullable SavepointManager savepointManager) { 071 this.savepointManager = savepointManager; 072 } 073 074 @Nullable 075 protected SavepointManager getSavepointManager() { 076 return this.savepointManager; 077 } 078 079 080 @Override 081 public void clear() { 082 super.clear(); 083 this.transactionActive = false; 084 this.savepointManager = null; 085 } 086 087}