加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 使用JDO持久化/检索Object时DataNucleus DAO对象中的Cla

发布时间:2020-12-15 02:22:12 所属栏目:Java 来源:网络整理
导读:我使用 Spring创建了一个简单的webapp. Jetty,我正在使用DataNucleus创建一个hello world JDO测试. DB4O. 我可以坚持一个类没有问题,但是当我去查询该类时我得到一个ClassCastException,无法将a.b.c.MyClass转换为a.b.c.MyClass. 当我检查我创建的原始对象的
我使用 Spring&创建了一个简单的webapp. Jetty,我正在使用DataNucleus&创建一个hello world JDO测试. DB4O.

我可以坚持一个类没有问题,但是当我去查询该类时我得到一个ClassCastException,无法将a.b.c.MyClass转换为a.b.c.MyClass.

当我检查我创建的原始对象的类加载器时,它是[WebAppClassLoader @ 1592226291],当然它是Spring WebApp类加载器.

我在同一个servlet方法中执行persist操作和查询操作,当我通过简单的查询从DB重新读取对象时,我从DB中获取了一组abcMyClass对象,但是类加载器是[sun. misc.Launcher$AppClassLoader@5acac268],因此例外.

遵循DataUucleus docs http://www.datanucleus.org/extensions/classloader_resolver.html

…the JDO2 class-loading mechanism
utilises 3 class loaders
* When creating the PersistenceManagerFactory you can
specify a class loader. This is used
first if specified
* The second class loader to try is the class loader for the current
thread.
* The third class loader to try is the class loader for the PMF context.

我介绍了记录的前两个选项,并验证了类加载器是Servlet中的WebAppClassLoader,以及servlet中的这些调试步骤:

Thread.currentThread().getContextClassLoader().toString()
((JDOPersistenceManagerFactory)pm.getPersistenceManagerFactory()).getPrimaryClassLoader().toString()

两者都将[WebAppClassLoader @ 1592226291]作为类加载器.

我不知道我在哪里错了.

解决方法

我之前的评论作为答案:

此异常表明它是类加载器问题.比较对象的类加载器和您用于转换的类.

ClassLoader loaderOfObject = theObject.getClass().getClassLoader();
ClassLoader loaderOfLocalClass = MyClass.getClassLoader();
// have to be the same.
assert loaderOfObject.equals(loaderOfLocalClass);

顺便说一句:如果db4o使用了错误的类加载器.您可以通过配置class-loader显式来更改它.

EmbeddedConfiguration configuration = Db4oEmbedded.newConfiguration();
    JdkReflector reflector = new JdkReflector(Thread.currentThread().getContextClassLoader());
    configuration.common().reflectWith(reflector);
    ObjectContainer container = Db4oEmbedded.openFile(configuration,"database.db4o");

当单个类加载器还不够时:您还可以传递db4o-interface JdkLoader的实例而不是类加载器.在那里,您可以实现任何类查找方法.例如,查找多个类加载器.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读