16

I'm trying to create a Union between two tables, using HQL (Hibernate Query Language). This SQL script works fine on my SQL server:

SELECT COUNT(DISTINCT linkedin_id) as test, school_name
FROM
(SELECT * FROM alum_education 
 UNION
 SELECT * FROM alum_connection_educations) AS UNIONS where school_name='some string'

the problem is, when i try to run it in grails like this:

     def countOfEdu = AlumEducation.executeQuery("select count (distinct linkedinId ) as countOfEdu, schoolName as SchoolName from (SELECT * FROM alumEducation UNION SELECT * FROM alumConnectionEducations) AS UNIONS where schoolName='some string'" )

i get this error:

  org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ( near line 1, column 83 [select count(distinct linkedinId )  as countOfEdu, schoolName as SchoolName  from (SELECT * FROM alumEducation UNION SELECT * FROM alumConnectionEducations) AS UNIONS where schoolName='Duquesne University']

How can I run the above SQL statement in grails?

thanks jason

jason
  • 3,821
  • 10
  • 63
  • 120

5 Answers5

41

Unions are not supported by HQL. There is an issue in Hibernate's JIRA that is open since 2005.

Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78
Andrey Adamovich
  • 20,285
  • 14
  • 94
  • 132
  • But is duplicated by "**[HHH-3971](https://hibernate.atlassian.net/browse/HHH-3971) Using UNION ALL , INTERSECTION functionality in hibernate**", and it was closed – Eduardo Cuomo Sep 04 '17 at 12:41
  • 1
    The issue HHH-1050 is now closed and says « Support for set operations (UNION, INTERSECT, EXCEPT) was added in Hibernate 6.0. » – Pascal Pixel Rigaux Aug 30 '22 at 21:12
1

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

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 used a method in JAVA for this solution. I hope I have contributed a bit, good luck to all...

Anto
  • 4,265
  • 14
  • 63
  • 113
Lanmaster
  • 29
  • 3
0

In your case, the real problem is that subqueries are not supported in FROM clause in EJBQL.

Babou
  • 1
0

Support for set operations (UNION, INTERSECT, EXCEPT) was added in Hibernate 6.0.

See the issue linked by Andrey Adamovich

0

You can always use native query to get result set.

Rohit Maurya
  • 57
  • 2
  • 8