简体   繁体   中英

Hibernate criteria equal on property

I have a Language:

class Language {
    private Site site;
    private Locale locale;
    //other usual stuff
}

I have a Site :

class Site {
    private Long id;
    private Set<Language> languages;
    private Locale primeLocale;
    //usual stuff
}

And I've been struggling for days to get primary language by site's id, is it even possible to filter by properties in hibernate? What i want is equivalent to this sql:

select *
from languages as l
join sites as s on l.locale = s.primeLocale
where l.siteId = (some id)

I tried following:

public Language getPrimeLanguageBySite(Long siteId) {
        Criteria criteria = session.createCriteria(Language.class).add(Restrictions.eq("site.id", siteId))
                .add(Restrictions.eq("site.primeLocale", Property.forName("locale")));
        return (Language)criteria.setMaxResults(1).uniqueResult();
    }

But it fails with unknown column 'site.primeLocale' in 'where clause' , and I can't even form my question without describing all this, so my attempts with google failed, could somebody please help? How can I get language by siteId and site's primeLocale?

You should use an alias and eqProperty.

public Language getPrimeLanguageBySite(Long siteId) {    
  Criteria c = session.createCriteria(Language.class, "language");   
  c.createAlias("language.site", "site");
  c.add(Restrictions.eqProperty("site.primeLocale", "language.locale"));
  c.add(Restrictions.eq("site.id", siteId));
  return c.setMaxResults(1).uniqueResult();
}

You can use an alias .

public Language getPrimeLanguageBySite(Long siteId) {    
  Criteria c = session.createCriteria(Language.class, "language");   
  c.createAlias("language.site", "site");
  c.add(Restrictions.eq("site.primeLocale", "language.locale"));
  c.add(Restrictions.eq("site.id", siteId));
  return c.setMaxResults(1).uniqueResult();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM