Search code examples
hibernaterequestfetchany

hibernate @Any mapping, can't fetch the "any" item


Using hibernate @Any mapping to map multiple entities in the same, I haven't be able to build a request to fetch all the objects of a specific class.

Hibernate doesn't seem to be capable to handle this kind of request.

My application doesn't start and throw the following error :

Invocation of init method failed; nested exception is java.lang.ClassCastException: org.hibernate.type.AnyType cannot be cast to org.hibernate.type.ComponentType

removing the part "left join fetch ic.item i" in the request solve this error.

For example, I've got the following model:

@Entity
@NamedQueries({
@NamedQuery(name = "GET_ITEMS", query = "from ItemContainer ic left join fetch ic.item i where ic.id=:containerId and ic.class=:clazz")})
public class ItemContainer {
.... 
    @Any(metaColumn = @Column(name = "TYPE"), fetch = FetchType.LAZY)
    @AnyMetaDef(idType = "long", metaType = "string", metaValues = { @MetaValue(targetEntity = Item1.class, value = "I1") })
    @JoinColumn(name = "TYPE_ID")
    private IItem item;
...
}

(with Item1 implements IItem)

And here is my DAO :

@Override
@SuppressWarnings("unchecked")
public List<ItemContainer> getItem1s(final Long containerId) {
return getHibernateTemplate().findByNamedQueryAndNamedParam("GET_ITEMS", new String[] { "containerId", "clazz" },
        new Object[] { containerId, Item1.class });
}

Is it just impossible, or am I missing something ?

Thanks


Solution

  • I had a similar issue, and after much headbanging I discovered that the "class" Hibernate was expecting was a class identifier, in this case the descriminator value.

    So using the above example, the solution was to query the class property as being I1:

    @Override
    @SuppressWarnings("unchecked")
    public List<ItemContainer> getItem1s(final Long containerId) {
    return getHibernateTemplate().findByNamedQueryAndNamedParam("GET_ITEMS", new String[] { "containerId", "clazz" },
            new Object[] { containerId, "I1" });
    }