DATAJPA-244 - Use ClassLoader of EntityManager for implementation lookup.

JpaClasUtils.isEntityManagerOfType(…) now uses the given EntityManager's ClassLoader to try to load the given concrete classname. We're actually using the EntityManager's delegate here which is usually some provider specific implementation (e.g. a Hibernate Session). This assumes that the ClassLoader who initially loaded the class to create the delegate instance will also see the special EntityManager interface.
This commit is contained in:
Oliver Gierke
2012-08-13 18:52:50 +02:00
parent 317dcc3cf1
commit 732d6ec261
2 changed files with 15 additions and 7 deletions

View File

@@ -24,6 +24,7 @@ import org.apache.openjpa.persistence.OpenJPAQuery;
import org.eclipse.persistence.jpa.JpaQuery;
import org.hibernate.ejb.HibernateQuery;
import org.springframework.data.jpa.repository.query.QueryExtractor;
import org.springframework.util.Assert;
/**
* Enumeration representing peristence providers to be used.
@@ -112,11 +113,13 @@ public enum PersistenceProvider implements QueryExtractor {
* Determines the {@link PersistenceProvider} from the given {@link EntityManager}. If no special one can be
* determined {@value #GENERIC_JPA} will be returned.
*
* @param em
* @return
* @param em must not be {@literal null}.
* @return will never be {@literal null}.
*/
public static PersistenceProvider fromEntityManager(EntityManager em) {
Assert.notNull(em);
for (PersistenceProvider provider : values()) {
if (isEntityManagerOfType(em, provider.entityManagerClassName)) {
return provider;

View File

@@ -17,6 +17,9 @@ package org.springframework.data.jpa.repository.utils;
import javax.persistence.EntityManager;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* Utility class to work with classes.
*
@@ -34,19 +37,21 @@ public abstract class JpaClassUtils {
/**
* Returns whether the given {@link EntityManager} is of the given type.
*
* @param em
* @param type the fully qualified expected {@link EntityManager} type.
* @param em must not be {@literal null}.
* @param type the fully qualified expected {@link EntityManager} type, must not be {@literal null} or empty.
* @return
*/
@SuppressWarnings("unchecked")
public static boolean isEntityManagerOfType(EntityManager em, String type) {
Assert.notNull(em, "EntityManager must not be null!");
Assert.hasText(type, "EntityManager type must not be null!");
try {
Class<? extends EntityManager> emType = (Class<? extends EntityManager>) Class.forName(type);
ClassLoader loader = em.getDelegate().getClass().getClassLoader();
Class<?> emType = ClassUtils.forName(type, loader);
emType.cast(em);
return true;
} catch (Exception e) {