Hibernate Criteria for Map key-value

孤街醉人 提交于 2019-12-22 09:27:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!