Using HQL to query on a Map's Values

南笙酒味 提交于 2019-12-08 07:37:45

问题


Let's say I have a map (call it myClass.mapElem<Object, Object>) like so:

Key    Val
A      X
B      Y
C      X

I want to write HQL that can query the Values such that I can get back all instances of myClass where mapElem's value is 'X' (where 'X' is a fully populated object-- I just don't want to go through each element and say x.e1 = mapElem.e1 and x.e2=... etc). I know I can do this for the keys by using where ? in index(myClass.mapElem), I just need the corresponding statement for querying the values!

Thanks in advance...

ETA: Not sure if the syntax makes a difference, but the way I am actually querying this is like so:

select myClass.something from myClass mc join myClass.mapElem me where...


回答1:


You should use elements(). I tried simulating your example with the following class

@Entity
@Table(name="Dummy")
public class TestClass {
    private Integer id;
    private Map<String, String> myMap;

    @Id
    @Column(name="DummyId")
    @GeneratedValue(generator="native")
    @GenericGenerator(name="native", strategy = "native")
    public Integer getId() {
        return id;
    }

    @ElementCollection
    public Map<String, String> getMyMap() {
        return myMap;
    }


    public void setId(Integer id) {
        this.id = id;
    }

    public void setMyMap(Map<String, String> myMap) {
        this.myMap = myMap;
    }
}

And persisted a few instances, which constain maps of a similar structure to what you have in your example. (using < String, String > since the values in your example are strings)

The following query gives me all instances of TestClass, where the map contains a specific value

SELECT DISTINCT myClass 
FROM TestClass myClass JOIN myClass.myMap myMap 
WHERE ? in elements(myMap)



回答2:


In my particular case, I ended up having to use an SQL query. Not ideal, but it worked.



来源:https://stackoverflow.com/questions/10804664/using-hql-to-query-on-a-maps-values

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