How to use key of MAP in Criteria Query?

kandarp picture kandarp · Feb 14, 2011 · Viewed 7.1k times · Source

I have a Bean like this

Class TestA
{
    Map<String,TestB> testBMap;
}

Class TestB
{
    String data;
    ...
}

I want to fetch the TestA data along with the map testBMap where key ='test1'.

How can i do this using Hibernate.

Answer

JB Nizet picture JB Nizet · Feb 14, 2011

The key must be the value of one of the persistent fields of TestB (let's says this field is names "foo"), so this code should work :

Criteria criteria = session.createCriteria(TestA.class, "a");
criteria.createAlias("a.testBMap", "b");
criteria.add(Restrictions.eq("b.foo", "test1"));
criteria.setFetchMode("a.testBMap", FetchMode.JOIN);
return criteria.list();