Java Hibernate 是否支持 UNION ALL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18296227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:12:12  来源:igfitidea点击:

Does Hibernate support UNION ALL?

javasqldatabasehibernatehql

提问by Brady Zhu

I'm a partial UI developer, right now I need to turn into Hibernate development. Today I occurred a problem in HQL when I'm trying to use UNION ALL, here is the HQL:

我是一个部分 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 

It shows error like this:

它显示如下错误:

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

And then I tried translate this HQL to raw SQL:

然后我尝试将此 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;

It normally shows the correct result, so I was thinking if Hibernate doesn't support UNION ALL syntax?

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

Thanks in advance.

提前致谢。

回答by Sean Carroll

There is a feature request still open for this https://hibernate.atlassian.net/browse/HHH-1050. Also take a look at Hibernate Union alternatives

https://hibernate.atlassian.net/browse/HHH-1050的功能请求仍处于开放状态。还可以看看Hibernate Union 替代方案

回答by user3632200

would like to share, which in my case, I found a situation that skirted this situation. The only rule here is to have the same type, in this case String, corresponding to return the list, could add as many tables you want:

想分享一下,就我而言,我发现了一种绕过这种情况的情况。这里唯一的规则是具有相同的类型,在本例中为 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;
}

I hope I have contributed a bit, good luck to all...

我希望我有所贡献,祝大家好运...