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

前端 未结 10 717
感情败类
感情败类 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:52

    I did not try this, but what happens when you use :status twice to check for NULL?

    Query query = getSession().createQuery(
         "from CountryDTO c where ( c.status = :status OR ( c.status IS NULL AND :status IS NULL ) ) and c.type =:type"
    )
    .setParameter("status", status, Hibernate.STRING)
    .setParameter("type", type, Hibernate.STRING);
    
    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
  • 2020-12-01 07:59

    HQL supports coalesce, allowing for ugly workarounds like:

    where coalesce(c.status, 'no-status') = coalesce(:status, 'no-status')
    
    0 讨论(0)
  • 2020-12-01 08:01

    The javadoc for setParameter(String, Object) is explicit, saying that the Object value must be non-null. It's a shame that it doesn't throw an exception if a null is passed in, though.

    An alternative is setParameter(String, Object, Type), which does allow null values, although I'm not sure what Type parameter would be most appropriate here.

    0 讨论(0)
提交回复
热议问题