Hibernate Criteria Queries, Part 2

Another strange issue with Hibernate Criteria queries…

Say you have a class Foo which has a one-to-one property mapping to a class to type Bar. The class Bar is a custom UserType implementation. The mapping might look as follows:

<property name="bar" type="uk.co.researchkitchen.usertype.Bar" column="bar" />

Now say you want to include this property in a Criteria query. Specifically, you want to query the property called name of the Bar class. As per the last pot I wrote about this, it seems logical that you would create a sub-criteria for the Bar property, and add an Expression on Bar.name, like so:


Criteria barCriteria = fooCriteria.createCriteria("bar");
barCriteria.add(Expression.eq("name""TestName"));

However, this doesn’t work. Hibernate theows a QueryException with the message “not an association type”. Stepping through the code, this happens when Hibernate internally creates an instance of a CustomType class to represent the UserType property that we are querying. Hibernate checks if the class is a composite or association type (of which CustomType is neither), and throws an Exception if it isn’t. However, you can get this to work by using the Example functionality of the Criteria class, as follows:


Foo foo = new Foo();
Bar barType = Bar.getInstance();
foo.setBar(barType);
hibCriteria.add(Example.create(foo));

Quite why this works and the former method doesn’t, I don’t know. I haven’t had time to look at it in detail. At least for now, there is a (slightly non-intuitive) workaround.

Leave a Reply