java 我可以在 HQL 查询中选择 null 作为列值吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3375762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I select null as a column value in HQL query?
提问by WSK
I need a list with three columns. column 1st and 3rd having values while 2nd as null. Can I do it through HQL query?
我需要一个包含三列的列表。第 1 和第 3 列具有值,而第 2 列为空。我可以通过 HQL 查询来完成吗?
I need something like this:
我需要这样的东西:
select id, null, name from MyClass
Where MyClass as well as underlying table has only two properties/columns ie, "id" and "name"
MyClass 以及基础表只有两个属性/列,即“id”和“name”
回答by Brian Deterling
Another option that seems to work (tested on DB2, MySQL, Oracle, and SQL Server):
另一个似乎有效的选项(在 DB2、MySQL、Oracle 和 SQL Server 上测试):
select id, cast(null as char), name from ...
You could subclass the Hibernate dialect and abstract it with a custom function:
您可以继承 Hibernate 方言并使用自定义函数对其进行抽象:
registerFunction("always_null",
new SQLFunctionTemplate(Hibernate.STRING, "cast(null as char)"));
and then use this in your HQL:
然后在你的 HQL 中使用它:
select id, always_null(), name from ...
回答by sohrab yousefi
You can use nullif()function to generate null.
您可以使用nullif()函数生成空值。
It accepts two arguments. If arguments are equal, it'll return nullvalue.
它接受两个参数。如果参数相等,它将返回null值。
回答by Pascal Thivent
AFAIK, your query won't return the expected result, it will only return the columns beforethe null(idin your case). However, the following would work
AFAIK,您的查询不会返回预期的结果,它只会返回(在您的情况下)之前的列。但是,以下将起作用nullid
select id as first, '', name from MyClass
I don't know if this is a bug or just a non supported feature (the HQL help: possible to "select NULL as ..."?thread on the Hibernate forums seems to suggest it's a bug).
我不知道这是一个错误还是只是一个不受支持的功能(HQL 帮助:可能“选择 NULL 作为...”?Hibernate 论坛上的线程似乎表明这是一个错误)。
I'm not sure I understood why you need this (could a select newexpression be an alternative?) but I'm afraid you'll have to use native SQL here.
我不确定我是否理解您为什么需要这个(select new表达式可以是替代方案吗?)但恐怕您必须在这里使用本机 SQL。
回答by Viktoriia Lymareva
You can also try TO_CHAR(null). It works fine for HQL- Oracle in constructor new Foo(id, name, attr3) where attr3 - String value
您也可以尝试 TO_CHAR(null)。它适用于构造函数 new Foo(id, name, attr3) where attr3 - String value 中的 HQL-Oracle

