如何在HQL中加入2个条件

时间:2018-01-02 09:52:04

标签: java sql hibernate orm hql

如何在HQL中加入2个条件?我想为以下查询编写HQL:

Pervious HQL:

StringBuffer sb = new StringBuffer();
        sb.append("from Hardwarekomponente h");
        sb.append(" left join fetch h.hwCategory4 c4");
        sb.append(" left join fetch c4.hwCategory3 c3");
        sb.append(" where h.konto.sisnetConfigSwitch = 1");
        sb.append(" and h.technischeNr is not null");
        sb.append(" and upper(c3.hwCategory3) like :cat3");

以前的SQL:

SELECT  *
FROM     HARDWAREKOMPONENTE h 
         INNER JOIN V_MD_HARDWARE_CAT4 c4 ON h.Hw_Kategorie4_Id=c4.Hardware_Cat4_Id 
         INNER JOIN V_MD_HARDWARE_CAT3 c3 ON c4.Hardware_Cat3_Id=c3.Hardware_Cat3_Id 
         LEFT OUTER JOIN V_MD_ACCOUNT k ON h.Konto_Id=k.Account_Id  
WHERE    (h.Technische_Nr is not null) and (upper(c3.Hardware_Cat3) like '%SWITCH%') and k.Sisnet_Config_Switch = 1;

但是现在由于一些变化,我想移动2个条件和join,以获得上一个查询没有给我的输出:

新的HQL(我正在尝试,但它与运营商的失败):

StringBuffer sb = new StringBuffer();
        sb.append("from Hardwarekomponente h ");
        sb.append(" left join fetch h.hwCategory4 c4 with (upper(c3.hwCategory3) like :cat3) ");
        sb.append(" left join fetch c4.hwCategory3 c3 with (h.konto.sisnetConfigSwitch = 1)  ");
        // sb.append(" where h.konto.kontoId = :account");
        sb.append(" where ");
        sb.append("  h.technischeNr is not null ");

新SQL:

SELECT  *
FROM     HARDWAREKOMPONENTE h 
         INNER JOIN V_MD_HARDWARE_CAT4 c4 ON h.Hw_Kategorie4_Id=c4.Hardware_Cat4_Id 
         INNER JOIN V_MD_HARDWARE_CAT3 c3 ON c4.Hardware_Cat3_Id=c3.Hardware_Cat3_Id AND (upper(c3.Hardware_Cat3) like '%SWITCH%')
         LEFT OUTER JOIN V_MD_ACCOUNT k ON h.Konto_Id=k.Account_Id AND k.Sisnet_Config_Switch = 1
WHERE    (h.Technische_Nr is not null);

所以,我的问题是如何添加或告诉Hibernate添加条件和连接?

1 个答案:

答案 0 :(得分:1)

在第一个with语句中,您指的是尚未定义的别名(c3)。

我会按如下方式构建查询:

StringBuffer sb = new StringBuffer();
  sb.append("from Hardwarekomponente h ");
  sb.append(" left join h.konto k with (k.sisnetConfigSwitch = 1)");  
  sb.append(" left join h.hwCategory4 c4");
  sb.append(" left join c4.hwCategory3 c3 with (upper(c3.hwCategory3) like :cat3) ");
  sb.append(" where ");
  sb.append("  h.technischeNr is not null ");