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 .nativeEntityManagerFactory == null) {
265: throw new IllegalStateException(
266: "JPA PersistenceProvider returned null EntityManagerFactory - check your JPA provider setup!");
267: }
268: if (this .jpaVendorAdapter != null) {
269: this .jpaVendorAdapter
270: .postProcessEntityManagerFactory(this .nativeEntityManagerFactory);
271: }
272:
273: // Wrap the EntityManagerFactory in a factory implementing all its interfaces.
274: // This allows interception of createEntityManager methods to return an
275: // application-managed EntityManager proxy that automatically joins
276: // existing transactions.
277: this .entityManagerFactory = createEntityManagerFactoryProxy(this .nativeEntityManagerFactory);
278: }
279:
280: /**
281: * Create a proxy of the given EntityManagerFactory. We do this to be able
282: * to return transaction-aware proxies for application-managed
283: * EntityManagers, and to introduce the NamedEntityManagerFactory interface
284: * @param emf EntityManagerFactory as returned by the persistence provider
285: * @return proxy entity manager
286: */
287: protected EntityManagerFactory createEntityManagerFactoryProxy(
288: EntityManagerFactory emf) {
289: // Automatically implement all interfaces implemented by the EntityManagerFactory.
290: Class[] ifcs = ClassUtils.getAllInterfaces(emf);
291: ifcs = (Class[]) ObjectUtils.addObjectToArray(ifcs,
292: EntityManagerFactoryInfo.class);
293: EntityManagerFactoryPlusOperations plusOperations = null;
294: if (getJpaDialect() != null
295: && getJpaDialect()
296: .supportsEntityManagerFactoryPlusOperations()) {
297: plusOperations = getJpaDialect()
298: .getEntityManagerFactoryPlusOperations(emf);
299: ifcs = (Class[]) ObjectUtils.addObjectToArray(ifcs,
300: EntityManagerFactoryPlusOperations.class);
301: }
302: return (EntityManagerFactory) Proxy.newProxyInstance(getClass()
303: .getClassLoader(), ifcs,
304: new ManagedEntityManagerFactoryInvocationHandler(emf,
305: this , plusOperations));
306: }
307:
308: /**
309: * Subclasses must implement this method to create the EntityManagerFactory
310: * that will be returned by the getObject() method
311: * @return EntityManagerFactory instance returned by this FactoryBean
312: * @throws PersistenceException if the EntityManager cannot be created
313: */
314: protected abstract EntityManagerFactory createNativeEntityManagerFactory()
315: throws PersistenceException;
316:
317: /**
318: * Implementation of the PersistenceExceptionTranslator interface, as
319: * autodetected by Spring's PersistenceExceptionTranslationPostProcessor.
320: * <p>Uses the dialect's conversion if possible; otherwise falls back to
321: * standard JPA exception conversion.
322: * @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor
323: * @see JpaDialect#translateExceptionIfPossible
324: * @see EntityManagerFactoryUtils#convertJpaAccessExceptionIfPossible
325: */
326: public DataAccessException translateExceptionIfPossible(
327: RuntimeException ex) {
328: return (this .jpaDialect != null ? this .jpaDialect
329: .translateExceptionIfPossible(ex)
330: : EntityManagerFactoryUtils
331: .convertJpaAccessExceptionIfPossible(ex));
332: }
333:
334: public EntityManagerFactory getNativeEntityManagerFactory() {
335: return this .nativeEntityManagerFactory;
336: }
337:
338: public PersistenceUnitInfo getPersistenceUnitInfo() {
339: return null;
340: }
341:
342: public DataSource getDataSource() {
343: return null;
344: }
345:
346: /**
347: * Return the singleton EntityManagerFactory.
348: */
349: public EntityManagerFactory getObject() {
350: return this .entityManagerFactory;
351: }
352:
353: public Class getObjectType() {
354: return (this .entityManagerFactory != null ? this .entityManagerFactory
355: .getClass()
356: : EntityManagerFactory.class);
357: }
358:
359: public boolean isSingleton() {
360: return true;
361: }
362:
363: /**
364: * Close the EntityManagerFactory on bean factory shutdown.
365: */
366: public void destroy() {
367: if (logger.isInfoEnabled()) {
368: logger
369: .info("Closing JPA EntityManagerFactory for persistence unit '"
370: + getPersistenceUnitName() + "'");
371: }
372: this .entityManagerFactory.close();
373: }
374:
375: /**
376: * Dynamic proxy invocation handler proxying an EntityManagerFactory to
377: * return a proxy EntityManager if necessary from createEntityManager()
378: * methods.
379: */
380: private static class ManagedEntityManagerFactoryInvocationHandler
381: implements InvocationHandler {
382:
383: private final EntityManagerFactory targetEntityManagerFactory;
384:
385: private final EntityManagerFactoryInfo entityManagerFactoryInfo;
386:
387: private final EntityManagerFactoryPlusOperations entityManagerFactoryPlusOperations;
388:
389: public ManagedEntityManagerFactoryInvocationHandler(
390: EntityManagerFactory targetEmf,
391: EntityManagerFactoryInfo emfInfo,
392: EntityManagerFactoryPlusOperations entityManagerFactoryPlusOperations) {
393:
394: this .targetEntityManagerFactory = targetEmf;
395: this .entityManagerFactoryInfo = emfInfo;
396: this .entityManagerFactoryPlusOperations = entityManagerFactoryPlusOperations;
397: }
398:
399: public Object invoke(Object proxy, Method method, Object[] args)
400: throws Throwable {
401: try {
402: if (method.getDeclaringClass().isAssignableFrom(
403: EntityManagerFactoryInfo.class)) {
404: return method.invoke(this .entityManagerFactoryInfo,
405: args);
406: }
407: if (method.getDeclaringClass().equals(
408: EntityManagerFactoryPlusOperations.class)) {
409: return method.invoke(
410: this .entityManagerFactoryPlusOperations,
411: args);
412: }
413: Object retVal = method.invoke(
414: this .targetEntityManagerFactory, args);
415: if (retVal instanceof EntityManager) {
416: EntityManager rawEntityManager = (EntityManager) retVal;
417: retVal = ExtendedEntityManagerCreator
418: .createApplicationManagedEntityManager(
419: rawEntityManager,
420: this .entityManagerFactoryInfo);
421: }
422: return retVal;
423: } catch (InvocationTargetException ex) {
424: throw ex.getTargetException();
425: }
426: }
427: }
428:
429: }
|