2011-08-24 13 views
10

Sto provando a creare un'unione tra due tabelle, usando HQL (Hibernate Query Language). Questo script SQL funziona bene sul mio server SQL:Come eseguire un'istruzione SQL Union in HQL?

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' 

Il problema è che quando provo a farlo funzionare in graal in questo modo:

 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'") 

ottengo questo errore:

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'] 

Come posso eseguire l'istruzione SQL sopra riportata in Grails?

grazie jason

+3

Eventuali duplicati: http://stackoverflow.com/questions/201023/hibernate-union-alternatives –

+0

eliminato commento – jellobird

risposta

37

organismi non sono supportati da HQL. C'è uno issue in JIRA di Hibernate che è aperto dal 2005.

+0

Ma viene duplicato da "** [HHH-3971] (https://hibernate.atlassian.net/browse/HHH-3971) Utilizzo di UNION ALL, funzionalità INTERSECTION in hibernate ** "ed è stato chiuso –

0

Nel tuo caso, il vero problema è che le sottoquery non sono supportate nella clausola FROM in EJBQL.

0

Mi piacerebbe condividere un modo che ho trovato per evitare questa situazione. L'unica regola qui è di avere lo stesso tipo, in questo caso una stringa, corrispondente al tipo della lista di ritorno, è possibile aggiungere tutte le tabelle che si desidera:

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; 
} 

ho usato un metodo in Java per questa soluzione. Spero di aver contribuito un po ', buona fortuna a tutti ...