Hibernate: How to set NULL query-parameter value with HQL?

前端 未结 10 750
感情败类
感情败类 2020-12-01 07:23

How can I set a Hibernate Parameter to \"null\"? Example:

Query query = getSession().createQuery(\"from CountryDTO c where c.status = :status  and c.type =:t         


        
10条回答
  •  春和景丽
    2020-12-01 07:54

    It seems you have to use is null in the HQL, (which can lead to complex permutations if there are more than one parameters with null potential.) but here is a possible solution:

    String statusTerm = status==null ? "is null" : "= :status";
    String typeTerm = type==null ? "is null" : "= :type";
    
    Query query = getSession().createQuery("from CountryDTO c where c.status " + statusTerm + "  and c.type " + typeTerm);
    
    if(status!=null){
        query.setParameter("status", status, Hibernate.STRING)
    }
    
    
    if(type!=null){
        query.setParameter("type", type, Hibernate.STRING)
    }
    

提交回复
热议问题