9

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.

Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
kandarp
  • 4,979
  • 11
  • 34
  • 43

4 Answers4

4

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();
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
3

In my case this did work fine:

countries = getSession().createCriteria( Country.class ).add( Restrictions.in( "region", regions ) )
                .createAlias( "name.translations", "translation" )
                .add( Restrictions.eq( "translation.indices", 'en' )).list();

The mapping is like this: Country has property name which is of type LocalizedText (an entity) LocalizedText contains Map<String, String> translations where key is language code and value is country name that corresponds to that language. So i had to create alias for translations and then user "magic" postfix ".indices" in eq().

eduyayo
  • 2,020
  • 2
  • 15
  • 35
YoMan78
  • 1,307
  • 2
  • 9
  • 15
2

Until Hibernate implements JPA's key() function (see HHH-5396), you can use the index() function:

session
    .createQuery("select a from TestA a join a.testBMap m where index(m) = :key")
    .setParameter("key", "test1")
    .list();
hertzsprung
  • 9,445
  • 4
  • 42
  • 77
1

This works for me:

Criteria criteria = session.createCriteria(TestA.class);
criteria.createAlias("testBMap", "t");
criteria.add(Restrictions.eq("t." + CollectionPropertyNames.COLLECTION_INDEX, "test1"));
return criteria.list();
Dee
  • 131
  • 1
  • 10