Hibernate:如何使用 HQL 设置 NULL 查询参数值? [英] Hibernate: How to set NULL query-parameter value with HQL?

查看:28
本文介绍了Hibernate:如何使用 HQL 设置 NULL 查询参数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将休眠参数设置为空"?示例:

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

Query query = getSession().createQuery("from CountryDTO c where c.status = :status  and c.type =:type")
.setParameter("status", status, Hibernate.STRING)
.setParameter("type", type, Hibernate.STRING);

就我而言,状态字符串可以为空.我已经调试了这个,然后休眠然后生成一个像这样的 SQL 字符串/查询 ....status = null... 然而这在 MYSQL 中不起作用,因为正确的 SQL 语句必须是status 为空"(根据我阅读的 mysql 文档,Mysql 不理解 status=null 并将其评估为 false,因此不会为查询返回任何记录...)

In my case, the status String can be null. I have debugged this and hibernate then generates an SQL string/query like this ....status = null... This however does not Work in MYSQL, as the correct SQL statement must be "status is null" (Mysql does not understand status=null and evaluates this to false so that no records will ever be returned for the query, according to the mysql docs i have read...)

我的问题:

  1. 为什么 Hibernate 不能将空字符串正确转换为is null"(而是错误地创建=null")?

  1. Why doesnt Hibernate translate a null string correctly to "is null" (and rather and wrongly creates "=null")?

重写此查询以使其为空安全的最佳方法是什么?使用 nullsafe 我的意思是,在状态"字符串为空的情况下,它应该创建一个为空"?

What is the best way to rewrite this query so that it is null-safe? With nullsafe I mean that in the case that the "status" String is null than it should create an "is null"?

推荐答案

  1. 我相信 hibernate 首先将您的 HQL 查询转换为 SQL,然后才尝试绑定您的参数.这意味着它将无法将查询从 param = ? 重写为 param is null.

尝试使用 Criteria api:

Try using Criteria api:

Criteria c = session.createCriteria(CountryDTO.class);
c.add(Restrictions.eq("type", type));
c.add(status == null ? Restrictions.isNull("status") : Restrictions.eq("status", status));
List result = c.list();

这篇关于Hibernate:如何使用 HQL 设置 NULL 查询参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆