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

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

    This is not a Hibernate specific issue (it's just SQL nature), and YES, there IS a solution for both SQL and HQL:

    @Peter Lang had the right idea, and you had the correct HQL query. I guess you just needed a new clean run to pick up the query changes ;-)

    The below code absolutely works and it is great if you keep all your queries in orm.xml

    from CountryDTO c where ((:status is null and c.status is null) or c.status = :status) and c.type =:type

    If your parameter String is null then the query will check if the row's status is null as well. Otherwise it will resort to compare with the equals sign.

    Notes:

    The issue may be a specific MySql quirk. I only tested with Oracle.

    The above query assumes that there are table rows where c.status is null

    The where clause is prioritized so that the parameter is checked first.

    The parameter name 'type' may be a reserved word in SQL but it shouldn't matter since it is replaced before the query runs.

    If you needed to skip the :status where_clause altogether; you can code like so:

    from CountryDTO c where (:status is null or c.status = :status) and c.type =:type

    and it is equivalent to:

    sql.append(" where ");
    if(status != null){
      sql.append(" c.status = :status and ");
    }
    sql.append(" c.type =:type ");
    

提交回复
热议问题