Permalink
Browse files

DATAJPA-244 - Use ClassLoader of EntityManager for implementation loo…

…kup.

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.
  • Loading branch information...
olivergierke committed Aug 13, 2012
1 parent 317dcc3 commit 732d6ec261fe834df79ae3bf049aa3d7eadd9b8b
@@ -24,6 +24,7 @@
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 @@ private PersistenceProvider(String entityManagerClassName) {
* 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;
@@ -17,6 +17,9 @@
import javax.persistence.EntityManager;
+import org.springframework.util.Assert;
+import org.springframework.util.ClassUtils;
+
/**
* Utility class to work with classes.
*
@@ -34,19 +37,21 @@ private 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) {

0 comments on commit 732d6ec

Please sign in to comment.