001: /*
002: * Copyright 2002-2007 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: * http://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:
017: package org.springframework.orm.jpa;
018:
019: import java.lang.reflect.InvocationHandler;
020: import java.lang.reflect.InvocationTargetException;
021: import java.lang.reflect.Method;
022: import java.lang.reflect.Proxy;
023: import java.util.HashMap;
024: import java.util.Iterator;
025: import java.util.Map;
026: import java.util.Properties;
027:
028: import javax.persistence.EntityManager;
029: import javax.persistence.EntityManagerFactory;
030: import javax.persistence.PersistenceException;
031: import javax.persistence.spi.PersistenceProvider;
032: import javax.persistence.spi.PersistenceUnitInfo;
033: import javax.sql.DataSource;
034:
035: import org.apache.commons.logging.Log;
036: import org.apache.commons.logging.LogFactory;
037:
038: import org.springframework.beans.BeanUtils;
039: import org.springframework.beans.factory.DisposableBean;
040: import org.springframework.beans.factory.FactoryBean;
041: import org.springframework.beans.factory.InitializingBean;
042: import org.springframework.dao.DataAccessException;
043: import org.springframework.dao.support.PersistenceExceptionTranslator;
044: import org.springframework.util.Assert;
045: import org.springframework.util.ClassUtils;
046: import org.springframework.util.CollectionUtils;
047: import org.springframework.util.ObjectUtils;
048:
049: /**
050: * Abstract {@link org.springframework.beans.factory.FactoryBean} that
051: * creates a local JPA {@link javax.persistence.EntityManagerFactory}
052: * instance within a Spring application context.
053: *
054: * <p>Encapsulates the common functionality between the different JPA
055: * bootstrap contracts (standalone as well as container).
056: *
057: * <p>Implements support for standard JPA configuration as well as
058: * Spring's {@link JpaVendorAdapter} abstraction, and controls the
059: * EntityManagerFactory's lifecycle.
060: *
061: * <p>This class also implements the
062: * {@link org.springframework.dao.support.PersistenceExceptionTranslator}
063: * interface, as autodetected by Spring's
064: * {@link org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor},
065: * for AOP-based translation of native exceptions to Spring DataAccessExceptions.
066: * Hence, the presence of e.g. LocalEntityManagerFactoryBean automatically enables
067: * a PersistenceExceptionTranslationPostProcessor to translate JPA exceptions.
068: *
069: * @author Juergen Hoeller
070: * @author Rod Johnson
071: * @since 2.0
072: * @see LocalEntityManagerFactoryBean
073: * @see LocalContainerEntityManagerFactoryBean
074: */
075: public abstract class AbstractEntityManagerFactoryBean implements
076: FactoryBean, InitializingBean, DisposableBean,
077: EntityManagerFactoryInfo, PersistenceExceptionTranslator {
078:
079: /** Logger available to subclasses */
080: protected final Log logger = LogFactory.getLog(getClass());
081:
082: private PersistenceProvider persistenceProvider;
083:
084: private String persistenceUnitName;
085:
086: private final Map jpaPropertyMap = new HashMap();
087:
088: private Class<? extends EntityManager> entityManagerInterface;
089:
090: private JpaDialect jpaDialect;
091:
092: private JpaVendorAdapter jpaVendorAdapter;
093:
094: /** Raw EntityManagerFactory as returned by the PersistenceProvider */
095: public EntityManagerFactory nativeEntityManagerFactory;
096:
097: private EntityManagerFactory entityManagerFactory;
098:
099: /**
100: * Set the PersistenceProvider implementation class to use for creating the
101: * EntityManagerFactory. If not specified, the persistence provider will be
102: * taken from the JpaVendorAdapter (if any) or retrieved through scanning
103: * (as far as possible).
104: * @see JpaVendorAdapter#getPersistenceProvider()
105: * @see javax.persistence.spi.PersistenceProvider
106: * @see javax.persistence.Persistence
107: */
108: public void setPersistenceProviderClass(
109: Class<? extends PersistenceProvider> persistenceProviderClass) {
110: Assert.isAssignable(PersistenceProvider.class,
111: persistenceProviderClass);
112: this .persistenceProvider = (PersistenceProvider) BeanUtils
113: .instantiateClass(persistenceProviderClass);
114: }
115:
116: /**
117: * Set the PersistenceProvider instance to use for creating the
118: * EntityManagerFactory. If not specified, the persistence provider
119: * will be taken from the JpaVendorAdapter (if any) or determined
120: * by the persistence unit deployment descriptor (as far as possible).
121: * @see JpaVendorAdapter#getPersistenceProvider()
122: * @see javax.persistence.spi.PersistenceProvider
123: * @see javax.persistence.Persistence
124: */
125: public void setPersistenceProvider(
126: PersistenceProvider persistenceProvider) {
127: this .persistenceProvider = persistenceProvider;
128: }
129:
130: public PersistenceProvider getPersistenceProvider() {
131: return this .persistenceProvider;
132: }
133:
134: /**
135: * Specify the name of the EntityManagerFactory configuration.
136: * <p>Default is none, indicating the default EntityManagerFactory
137: * configuration. The persistence provider will throw an exception if
138: * ambiguous EntityManager configurations are found.
139: * @see javax.persistence.Persistence#createEntityManagerFactory(String)
140: */
141: public void setPersistenceUnitName(String persistenceUnitName) {
142: this .persistenceUnitName = persistenceUnitName;
143: }
144:
145: public String getPersistenceUnitName() {
146: return this .persistenceUnitName;
147: }
148:
149: /**
150: * Specify JPA properties, to be passed into
151: * <code>Persistence.createEntityManagerFactory</code> (if any).
152: * <p>Can be populated with a String "value" (parsed via PropertiesEditor) or a
153: * "props" element in XML bean definitions.
154: * @see javax.persistence.Persistence#createEntityManagerFactory(String, java.util.Map)
155: * @see javax.persistence.spi.PersistenceProvider#createContainerEntityManagerFactory(javax.persistence.spi.PersistenceUnitInfo, java.util.Map)
156: */
157: public void setJpaProperties(Properties jpaProperties) {
158: CollectionUtils.mergePropertiesIntoMap(jpaProperties,
159: this .jpaPropertyMap);
160: }
161:
162: /**
163: * Specify JPA properties as a Map, to be passed into
164: * <code>Persistence.createEntityManagerFactory</code> (if any).
165: * <p>Can be populated with a "map" or "props" element in XML bean definitions.
166: * @see javax.persistence.Persistence#createEntityManagerFactory(String, java.util.Map)
167: * @see javax.persistence.spi.PersistenceProvider#createContainerEntityManagerFactory(javax.persistence.spi.PersistenceUnitInfo, java.util.Map)
168: */
169: public void setJpaPropertyMap(Map jpaProperties) {
170: if (jpaProperties != null) {
171: this .jpaPropertyMap.putAll(jpaProperties);
172: }
173: }
174:
175: /**
176: * Allow Map access to the JPA properties to be passed to the persistence
177: * provider, with the option to add or override specific entries.
178: * <p>Useful for specifying entries directly, for example via
179: * "jpaPropertyMap[myKey]".
180: */
181: public Map getJpaPropertyMap() {
182: return this .jpaPropertyMap;
183: }
184:
185: /**
186: * Specify the (potentially vendor-specific) EntityManager interface that
187: * this factory's EntityManagers are supposed to implement.
188: * <p>The default will be taken from the specific JpaVendorAdapter, if any,
189: * or set to the standard <code>javax.persistence.EntityManager</code>
190: * interface else.
191: * @see JpaVendorAdapter#getEntityManagerInterface()
192: * @see EntityManagerFactoryInfo#getEntityManagerInterface()
193: */
194: public void setEntityManagerInterface(
195: Class<? extends EntityManager> entityManagerInterface) {
196: Assert
197: .isAssignable(EntityManager.class,
198: entityManagerInterface);
199: this .entityManagerInterface = entityManagerInterface;
200: }
201:
202: public Class<? extends EntityManager> getEntityManagerInterface() {
203: return this .entityManagerInterface;
204: }
205:
206: /**
207: * Specify the vendor-specific JpaDialect implementation to associate with
208: * this EntityManagerFactory. This will be exposed through the
209: * EntityManagerFactoryInfo interface, to be picked up as default dialect by
210: * accessors that intend to use JpaDialect functionality.
211: * @see EntityManagerFactoryInfo#getJpaDialect()
212: */
213: public void setJpaDialect(JpaDialect jpaDialect) {
214: this .jpaDialect = jpaDialect;
215: }
216:
217: public JpaDialect getJpaDialect() {
218: return this .jpaDialect;
219: }
220:
221: /**
222: * Specify the JpaVendorAdapter implementation for the desired JPA provider,
223: * if any. This will initialize appropriate defaults for the given provider,
224: * such as persistence provider class and JpaDialect, unless locally
225: * overridden in this FactoryBean.
226: */
227: public void setJpaVendorAdapter(JpaVendorAdapter jpaVendorAdapter) {
228: this .jpaVendorAdapter = jpaVendorAdapter;
229: }
230:
231: public final void afterPropertiesSet() throws PersistenceException {
232: if (this .jpaVendorAdapter != null) {
233: if (this .persistenceProvider == null) {
234: this .persistenceProvider = this .jpaVendorAdapter
235: .getPersistenceProvider();
236: }
237: Map vendorPropertyMap = this .jpaVendorAdapter
238: .getJpaPropertyMap();
239: if (vendorPropertyMap != null) {
240: for (Iterator it = vendorPropertyMap.entrySet()
241: .iterator(); it.hasNext();) {
242: Map.Entry entry = (Map.Entry) it.next();
243: if (!this .jpaPropertyMap
244: .containsKey(entry.getKey())) {
245: this .jpaPropertyMap.put(entry.getKey(), entry
246: .getValue());
247: }
248: }
249: }
250: if (this .entityManagerInterface == null) {
251: this .entityManagerInterface = this .jpaVendorAdapter
252: .getEntityManagerInterface();
253: }
254: if (this .jpaDialect == null) {
255: this .jpaDialect = this .jpaVendorAdapter.getJpaDialect();
256: }
257: } else {
258: if (this .entityManagerInterface == null) {
259: this .entityManagerInterface = EntityManager.class;
260: }
261: }
262:
263: this .nativeEntityManagerFactory = createNativeEntityManagerFactory();
264: if (this .jpaVendorAdapter != null) {
265: this .jpaVendorAdapter
266: .postProcessEntityManagerFactory(this .nativeEntityManagerFactory);
267: }
268:
269: // Wrap the EntityManagerFactory in a factory implementing all its interfaces.
270: // This allows interception of createEntityManager methods to return an
271: // application-managed EntityManager proxy that automatically joins
272: // existing transactions.
273: this .entityManagerFactory = createEntityManagerFactoryProxy(this .nativeEntityManagerFactory);
274: }
275:
276: /**
277: * Create a proxy of the given EntityManagerFactory. We do this to be able
278: * to return transaction-aware proxies for application-managed
279: * EntityManagers, and to introduce the NamedEntityManagerFactory interface
280: * @param emf EntityManagerFactory as returned by the persistence provider
281: * @return proxy entity manager
282: */
283: protected EntityManagerFactory createEntityManagerFactoryProxy(
284: EntityManagerFactory emf) {
285: // Automatically implement all interfaces implemented by the EntityManagerFactory.
286: Class[] ifcs = ClassUtils.getAllInterfaces(emf);
287: ifcs = (Class[]) ObjectUtils.addObjectToArray(ifcs,
288: EntityManagerFactoryInfo.class);
289: EntityManagerFactoryPlusOperations plusOperations = null;
290: if (getJpaDialect() != null
291: && getJpaDialect()
292: .supportsEntityManagerFactoryPlusOperations()) {
293: plusOperations = getJpaDialect()
294: .getEntityManagerFactoryPlusOperations(emf);
295: ifcs = (Class[]) ObjectUtils.addObjectToArray(ifcs,
296: EntityManagerFactoryPlusOperations.class);
297: }
298: return (EntityManagerFactory) Proxy.newProxyInstance(getClass()
299: .getClassLoader(), ifcs,
300: new ManagedEntityManagerFactoryInvocationHandler(emf,
301: this , plusOperations));
302: }
303:
304: /**
305: * Subclasses must implement this method to create the EntityManagerFactory
306: * that will be returned by the getObject() method
307: * @return EntityManagerFactory instance returned by this FactoryBean
308: * @throws PersistenceException if the EntityManager cannot be created
309: */
310: protected abstract EntityManagerFactory createNativeEntityManagerFactory()
311: throws PersistenceException;
312:
313: /**
314: * Implementation of the PersistenceExceptionTranslator interface, as
315: * autodetected by Spring's PersistenceExceptionTranslationPostProcessor.
316: * <p>Uses the dialect's conversion if possible; otherwise falls back to
317: * standard JPA exception conversion.
318: * @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor
319: * @see JpaDialect#translateExceptionIfPossible
320: * @see EntityManagerFactoryUtils#convertJpaAccessExceptionIfPossible
321: */
322: public DataAccessException translateExceptionIfPossible(
323: RuntimeException ex) {
324: return (this .jpaDialect != null ? this .jpaDialect
325: .translateExceptionIfPossible(ex)
326: : EntityManagerFactoryUtils
327: .convertJpaAccessExceptionIfPossible(ex));
328: }
329:
330: public EntityManagerFactory getNativeEntityManagerFactory() {
331: return this .nativeEntityManagerFactory;
332: }
333:
334: public PersistenceUnitInfo getPersistenceUnitInfo() {
335: return null;
336: }
337:
338: public DataSource getDataSource() {
339: return null;
340: }
341:
342: /**
343: * Return the singleton EntityManagerFactory.
344: */
345: public EntityManagerFactory getObject() {
346: return this .entityManagerFactory;
347: }
348:
349: public Class getObjectType() {
350: return (this .entityManagerFactory != null ? this .entityManagerFactory
351: .getClass()
352: : EntityManagerFactory.class);
353: }
354:
355: public boolean isSingleton() {
356: return true;
357: }
358:
359: /**
360: * Close the EntityManagerFactory on bean factory shutdown.
361: */
362: public void destroy() {
363: if (logger.isInfoEnabled()) {
364: logger
365: .info("Closing JPA EntityManagerFactory for persistence unit '"
366: + getPersistenceUnitName() + "'");
367: }
368: this .entityManagerFactory.close();
369: }
370:
371: /**
372: * Dynamic proxy invocation handler proxying an EntityManagerFactory to
373: * return a proxy EntityManager if necessary from createEntityManager()
374: * methods.
375: */
376: private static class ManagedEntityManagerFactoryInvocationHandler
377: implements InvocationHandler {
378:
379: private final EntityManagerFactory targetEntityManagerFactory;
380:
381: private final EntityManagerFactoryInfo entityManagerFactoryInfo;
382:
383: private final EntityManagerFactoryPlusOperations entityManagerFactoryPlusOperations;
384:
385: public ManagedEntityManagerFactoryInvocationHandler(
386: EntityManagerFactory targetEmf,
387: EntityManagerFactoryInfo emfInfo,
388: EntityManagerFactoryPlusOperations entityManagerFactoryPlusOperations) {
389:
390: this .targetEntityManagerFactory = targetEmf;
391: this .entityManagerFactoryInfo = emfInfo;
392: this .entityManagerFactoryPlusOperations = entityManagerFactoryPlusOperations;
393: }
394:
395: public Object invoke(Object proxy, Method method, Object[] args)
396: throws Throwable {
397: try {
398: if (method.getDeclaringClass().isAssignableFrom(
399: EntityManagerFactoryInfo.class)) {
400: return method.invoke(this .entityManagerFactoryInfo,
401: args);
402: }
403: if (method.getDeclaringClass().equals(
404: EntityManagerFactoryPlusOperations.class)) {
405: return method.invoke(
406: this .entityManagerFactoryPlusOperations,
407: args);
408: }
409: Object retVal = method.invoke(
410: this .targetEntityManagerFactory, args);
411: if (retVal instanceof EntityManager) {
412: EntityManager rawEntityManager = (EntityManager) retVal;
413: retVal = ExtendedEntityManagerCreator
414: .createApplicationManagedEntityManager(
415: rawEntityManager,
416: this .entityManagerFactoryInfo);
417: }
418: return retVal;
419: } catch (InvocationTargetException ex) {
420: throw ex.getTargetException();
421: }
422: }
423: }
424:
425: }
|