4

我是一名部分 UI 开发人员,现在我需要转入 Hibernate 开发。今天,当我尝试使用 UNION ALL 时,我在 HQL 中遇到了一个问题,这里是 HQL:

SELECT COUNT(DISTINCT users.userId) AS totalSize FROM (SELECT DISTINCT 
d1.sponsor.id AS userId FROM Dating d1 WHERE d1.invitee.id = ? UNION ALL 
SELECT DISTINCT d2.invitee.id AS userId FROM Dating d2 WHERE d2.sponsor.id = ?) 
AS users 

它显示如下错误:

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 55

然后我尝试将此 HQL 转换为原始 SQL:

SELECT COUNT(DISTINCT users.userId) AS totalSize FROM (SELECT DISTINCT 
d1.sponsorId AS userId FROM mmy_dating d1 WHERE d1.inviteeId = 6 UNION 
ALL SELECT DISTINCT d2.inviteeId AS userId FROM mmy_dating d2 WHERE 
d2.sponsorId = 6) AS users;

它通常会显示正确的结果,所以我在想 Hibernate 是否不支持 UNION ALL 语法?

提前致谢。

4

2 回答 2

6

此https://hibernate.atlassian.net/browse/HHH-1050仍有一个功能请求开放。还可以看看Hibernate Union 的替代品

于 2013-08-18T06:14:12.023 回答
0

想分享一下,就我而言,我发现了一种绕过这种情况的情况。这里唯一的规则是具有相同的类型,在这种情况下,对应于返回列表的 String 可以添加任意数量的表:

public List<String> findByCPForCNPJ(String query){
    TypedQuery<String> ccpf = manager.createQuery("select cpf from PessoaFisica where cpf like :pCpf", String.class);
    ccpf.setParameter("pCpf", "%" + query + "%");
    List<String> lista1 = ccpf.getResultList();

    TypedQuery<String> ccnpj = manager.createQuery("select cnpj from PessoaJuridica where cnpj like :pCnpj", String.class);
    ccnpj.setParameter("pCnpj", "%" + query + "%");

    lista1.addAll(ccnpj.getResultList());
    return lista1;
}

我希望我贡献了一点,祝大家好运......

于 2014-12-19T15:57:49.510 回答