问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/16401550/hibernate-criteria-for-map-key-value