HQL内部联接查询排除ManyToOne集成员

时间:2015-06-26 10:51:19

标签: java hibernate hql

我有翻译课,例如:

 class Translation{
      String key;
      String type;
      String userId;
      @OneToMany
      Set<TranslationValue> translations;
 }

与TranslationValue类保持OneToMany关系,例如:

 class TranslationValue{
      String language;
      String value;
      @ManyToOne
      Translation translation;
 }

我想基于TranslationValue.language成员进行查询,并返回包含只有1个TranslationValue对象的集合的翻译对象列表 - &gt;用作查询参数的那个,例如:

translationDao.findAllForLanguage("en");

这将返回db中具有TranslationValue.language =“en”的每个翻译对象,并且还将从每个对象中删除其中语言不是“en”的Translation.translations。

到目前为止,我正在返回所有Translation对象的列表,这些对象在各自的翻译集中具有带有language =“en”成员的TranslationValue对象。我需要删除所有没有language =“en”的TranslationValue对象。

编辑:进展

此查询返回正确的匹配数量,但所有值均为null。 - &GT;

 @Override
public List<Translation> findAllForLanguage2(String language) {
    //TODO:finish
    final Query query = entityManager.createQuery(
            "select new " + getDomain().getSimpleName() + "(t.key,t.clientName,t.userId,t.type,t.platform,tv) from " + getDomain().getSimpleName() + " t right join t.translations tv where tv = some(from tv where tv.language = :language)");
    query.setParameter("language", language);


    return query.getResultList();
}

printing all from query
translation: Translation{key='null', clientName='null', userId='null', type=null, platform='null', translations=null}
translation: Translation{key='null', clientName='null', userId='null', type=null, platform='null', translations=null}
translation: Translation{key='null', clientName='null', userId='null', type=null, platform='null', translations=null}
translation: Translation{key='null', clientName='null', userId='null', type=null, platform='null', translations=null}
translation: Translation{key='null', clientName='null', userId='null', type=null, platform='null', translations=null}
translation: Translation{key='null', clientName='null', userId='null', type=null, platform='null', translations=null}

此查询返回一个Object [],其中第二个对象实际上是我想要的TranslationValue对象,但是Translation对象为null - &gt;

    @Override
public List<Object> findAllForLanguage(String language) {
    //TODO:finish
    final Query query = entityManager.createQuery(
            "from " + getDomain().getSimpleName() + " t full join t.translations tv where tv = some(from tv where tv.language = :language))");
    query.setParameter("language", language);


    return query.getResultList();
}

printing all from query
null
TranslationValue{language='en', value='feed'}
null
TranslationValue{language='en', value='feed'}
null
TranslationValue{language='en', value='broken'}
null
TranslationValue{language='en', value='broken'}
null
TranslationValue{language='en', value='water'}
null
TranslationValue{language='en', value='broken'}

1 个答案:

答案 0 :(得分:0)

此查询应该没问题

select t from Translation t join t.translations tv 
where tv.language = :language 
and size(t.translations) = 1