5

I have the following property in my hibernate entity:

@ElementCollection(targetClass = String.class, fetch = FetchType.EAGER)
@CollectionTable(name="FORMDATA", joinColumns = @JoinColumn(name="FORM_ID"))
private Map<String, String> formData;

I want to do a query with hibernate Criteria where I want to match a form with a given key-value pair, something like this:

criteria.add(Restrictions.like("formdata.key", "%"+value+"%").ignoreCase());

where 'key' and 'value' are passed via method parameters.

Anyone knows how this should work? For me the hibernate documentation is not clear on this.

Thanks a lot, B.

b.maes
  • 55
  • 1
  • 6

1 Answers1

5

Since I had the same question myself, I did some trial and error and came up with this solution:

Criteria attr = crit.createCriteria("formdata");
attr.add(Restrictions.and(
            Restrictions.eq("indices", key), 
            Restrictions.eq("elements", "%" + value + "%")
));

The "indices" and "elements" are special properties of collections that can be used to access the key and value of the mapped, uh, Map. But apparently only in a sub-criterion on that property -- a crit.add(Restrictions.eq("formdata.indices", "foo")) does not work.

I also haven't found a way to query on multiple elements of the mapped collection. The generated SQL always only generates a single join to the collection table.

creinig
  • 1,560
  • 12
  • 23