Hibernate Criteria for Map key-value
Asked Answered
D

1

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.

Descry answered 6/5, 2013 at 15:1 Comment(0)
C
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.

Copland answered 10/7, 2013 at 11:22 Comment(1)
It also works with sorting: attr.addOrder(Order.asc("elements"));Geomorphic

© 2022 - 2024 — McMap. All rights reserved.