ObjectDB ObjectDB

java.lang.ClassCastException in OSGi runtime when loading data from DB



I'm trying to use ObjectDB in an OSGi environment (Karaf 4.0.7).

I'm now facing ClassCastExceptions on my "entity" classes when I try to read data from the DB.

In a very old (2011?) forum entry this problem was already discussed and it appears to be related to classloader problems.

My entity is a dedicated bundle.

I have one bundle with the database service (doing the actual objectdb actions -> persist, query etc).

I have one business bundle that handles the "business" actions.

The entity obviously has to get loaded by all bundles in order to manipulate the data.

This is the code that seems to throw the exception:

public Person loadPerson(final Integer id) {
  TypedQuery<Person> typedQuery = entityManager.createQuery("SELECT FROM Person p WHERE p.id = 1", Person.class);
  Person singleResult = typedQuery.getSingleResult();
  return singleResult;

Is there a solution to this problem?

I'm not sure if restricting the use of the Entity class to the database service only and the using DTOs could solve the problem but I would mean doubling the classes and having to move data around between the Entities and DTOs.

Many thanks in advance for your support,



The ClassCastException probably indicates that the Person class is available from two different class loaders:

  1. A Person class that is specified in your query.
  2. A Person class that is available to ObjectDB.

To eliminate the ClassCastException you must make sure that only one shared class loader is used by both ObjectDB and your bundle that uses ObjectDB. 

ObjectDB Support


the objectdb.jar file being deployed as a standard bundle I can't control it's classloader.

Messing around with classloaders is not best practice in OSGi. Especially am I wondering how I should get this working when I have multiple bundles using objectdb (e.g. Person, Buildings, Departments, Hardware etc). All of these bundles will persist and manipulate entities persisted in objectdb.

Is there a better way to solve this? Do you by any change have some sample projects for OSGi?

I hope I don't have to drop objectdb as I just ordered my first server license...




Some ObjectDB users make extensive use of OSGi with ObjectDB including multiple bundles with entity classes. Unfortunately we do not have a reference project, and since we do not develop OSGi bundles it seems that probably we are not aware of all the possibilities and settings. Maybe there are other solutions that do not require setting the context class loader. However, to avoid duplication of classes on retrieval of objects ObjectDB must have access to the same class loader that is used by the bundle that uses ObjectDB to load the entity classes.

ObjectDB Support


To post on this website please sign in.