Eclipselink with MongoDB java.lang.ClassCastException

折月煮酒 提交于 2019-12-02 04:20:57

The problem was with my persistence unit. By default ALL the Entity classes are included, So both my NoSQL and SQL entities were being passed to both the SQL and the NoSQL persistence units. The solution was just to specify the entities inside the persistence.xml persistence unit.

<persistence-unit name="Dastrax_NoSQL_PU" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>declare_your_entity_1</class>
    <class>declare_your_entity_2</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="eclipselink.target-database" value="org.eclipse.persistence.nosql.adapters.mongo.MongoPlatform"/>
      <property name="eclipselink.nosql.connection-spec" value="org.eclipse.persistence.nosql.adapters.mongo.MongoConnectionSpec"/>
      <property name="eclipselink.nosql.property.mongo.port" value="27017"/>
      <property name="eclipselink.nosql.property.mongo.host" value="localhost"/>
      <property name="eclipselink.nosql.property.mongo.db" value="dev"/>
      <property name="eclipselink.logging.level" value="FINEST"/>
    </properties>
  </persistence-unit>

I got the ClassCastException with EclipseLink 2.6.0. Turned out it was a bug and it is fixed in 2.6.1

https://www.eclipse.org/eclipselink/downloads/milestones.php

Bug: https://www.eclipse.org/forums/index.php/t/1068464/

Note: At this moment 2.6.1 is not officially released but it worked great for me so far.

I think the correct answer would contain true in the exclude-unlisted-classes field. In other words, it would exclude the entity classes not belonging to the NoSQL JPA. Therefore, the persistence.xml should look as follows:

<persistence-unit name="Dastrax_NoSQL_PU" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>declare_your_entity_1</class>
    <class>declare_your_entity_2</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <property name="eclipselink.target-database" value="org.eclipse.persistence.nosql.adapters.mongo.MongoPlatform"/>
      <property name="eclipselink.nosql.connection-spec" value="org.eclipse.persistence.nosql.adapters.mongo.MongoConnectionSpec"/>
      <property name="eclipselink.nosql.property.mongo.port" value="27017"/>
      <property name="eclipselink.nosql.property.mongo.host" value="localhost"/>
      <property name="eclipselink.nosql.property.mongo.db" value="dev"/>
      <property name="eclipselink.logging.level" value="FINEST"/>
    </properties>
  </persistence-unit>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!