sql >> Base de Datos >  >> RDS >> Oracle

Hibernate Create Criteria para unirse a la misma tabla dos veces:probé 2 enfoques con 2 errores de diferencia

Hay un antiguo error de Hibernate HHH-879 sobre el problema de org.hibernate.QueryException: duplicate association path abierto en 2005 y sigue abierto...

Otro problema se cierra sin solución HHH-7882

Entonces la opción 1) no es adecuada.

Pero en los comentarios del error anterior hay una solución alternativa útil se menciona usando exists

Así que usa dos veces sqlRestriction con exists y una subconsulta correlacionada que filtra la categoría adecuada. Obtendrá solo empresas conectado a ambas categorías.

crit.add( Restrictions.sqlRestriction( 
  "exists (select null from Company_Customercategory a where {alias}.company_Id = a.company_Id and a.CUSTOMERCATEGORYID = ?)",
  1, IntegerType.INSTANCE ) );
crit.add( Restrictions.sqlRestriction( 
  "exists (select null from Company_Customercategory a where {alias}.company_Id = a.company_Id and a.CUSTOMERCATEGORYID = ?)",
  6, IntegerType.INSTANCE ) );

Esto lleva a la siguiente consulta que proporciona el resultado correcto

select this_.COMPANY_ID as COMPANY_ID1_2_0_, this_.COMPANY_NAME as COMPANY_NAME2_2_0_ 
from COMPANIES this_ 
where exists (select null from Company_Customercategory a 
              where this_.company_Id = a.company_Id and a.CUSTOMERCATEGORYID =  ?) and 
      exists (select null from Company_Customercategory a 
              where this_.company_Id = a.company_Id and a.CUSTOMERCATEGORYID = ?)