带有Eclipselink的内存中ClassLoader

时间:2015-07-20 11:22:20

标签: jpa eclipselink

我有一个内存类加载器,用于加载JPA-Entity。

 private static class InMemoryClassLoader extends ClassLoader {
    private final Map<String, ByteJavaFileObject> fileObjects = new HashMap<>();
    private final Map<String, Class<?>> cachedClasses = new HashMap<>();


    public InMemoryClassLoader(ClassLoader parent) {
        super(parent);
    }

    @Override
    protected Class<?> findClass(String className) throws ClassNotFoundException {
        if (fileObjects.containsKey(className)) {
            if (!cachedClasses.containsKey(className)) {
                ByteJavaFileObject fileObject = fileObjects.get(className);
                cachedClasses.put(className, defineClass(className, fileObject.getByteCode(), 0, fileObject.getByteCode().length));
            }
            return cachedClasses.get(className);
        } else {
            return super.findClass(className);
        }
    }

   @Override
   public Class<?> loadClass(String className) throws ClassNotFoundException {
        if (fileObjects.containsKey(className)) {
           return findClass(className);
        } else {
            return super.loadClass(className);
        }
    }

    @Override
    public InputStream getResourceAsStream(String className) {
       return new ByteArrayInputStream(fileObjects.get(className).getByteCode());
    }
...
}

我使用这个Classloader创建了一个EntityManagerFactory。

 Map<String, Object> properties = new HashMap<>();
 properties.put("eclipselink.classloader", inMemoryClassLoader);
 EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("pack", properties);
 entityManager = entityManagerFactory.createEntityManager();

现在,当我尝试预先加载正确注释的类然后使用它(entityManager.find(inMemoryClassLoader.findClass("pack.test"), 0))时,我得到以下异常。

java.lang.IllegalArgumentException: Unknown entity bean class: class pack.test, please verify that this class has been marked with the @Entity annotation.

我的 persistence.xml 如下所示:

<persistence-unit name="pack">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>

    <class>pack.test</class>
    <properties>
        ... // properties tested
    </properties>
</persistence-unit>

我做了大量的研究,但找不到任何人试图做我想做同样事情的例子。基本上我想编译并加载在运行时生成的类字符串而不将文件保存到光盘。之后我想使用这些文件来获取数据库条目。 (用于测试目的)

1 个答案:

答案 0 :(得分:1)

不确定这是否适合您的使用案例,但您是否在EclipseLink中检查了dynamic persistence