Type for TypedQuery incompatible with query return type.

I was playing around with an OSGi/Hibernate sample application that was using Apache Aries to provide EntityManagers to bundles and ran into a weird issue when I began querying. Take the following code:

TypedQuery<User> query = em.createQuery("FROM User", User.class);
List<User> users = query.getResultList();

At runtime, createQuery would throw “Type specified for TypedQuery [com.page5of4.ms.examples.subscriber.model.User] is incompatible with query return type [interface java.util.Map]” which was very confusing. After some digging, I discovered this code deep inside Hibernate (EntityType)

private Class determineAssociatedEntityClass() {
  try {
    return ReflectHelper.classForName(getAssociatedEntityName());
  }
  catch (ClassNotFoundException cnfe) {
    return java.util.Map.class;
  }
}

Suddenly this is a common OSGi problem. ReflectHelper.classForName does what anybody familiar with OSGi class loading peculiarities would imagine – tries to use the TCCL and then falls back on Class.forName.  This took me some time to uncover and is fairly obscure given the error I was seeing and so I figured I’d write this post to help anybody else that runs into the same issue. You can avoid the problem a few ways:

  1. Export your model packages assuming DynamicImport-Package is enabled on whatever Hibernate bundle you’re using.
  2. Use non-TypedQuery createQuery (meh)

I’m still pretty new to this OSGi stuff so if there’s a better solution I’d love to hear about it… Hope this helps somebody!

Advertisements

One thought on “Type for TypedQuery incompatible with query return type.

  1. GRudiD

    Hi, i’m facing the same problem with Hibernate 5.1.0 and Glassfish 4.1 at the moment. Typed queries are quite nice in my opinion and i would like to avoid to remove them from my project. But what exactly do you mean with your first solution “Export your model packages assuming DynamicImport-Package is enabled on whatever Hibernate bundle you’re using.”?

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s