views:

76

answers:

2

I need a list with three columns. column 1st and 3rd having values while 2nd as null. Can I do it through HQL query?

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"

+1  A: 

AFAIK, your query won't return the expected result, it will only return the columns before the null (id in your case). However, the following would work

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).

I'm not sure I understood why you need this (could a select new expression be an alternative?) but I'm afraid you'll have to use native SQL here.

Pascal Thivent
"select new Object(id, null, name) from MyClass" doesn't work as well
Leslie Norman
@SJP Yes, I know but that's not what I meant. I meant using `new Foo(id, name)` and setting a third attribute to `null` in the constructor.
Pascal Thivent
@Pascal oh, I missed your point in first attempt now got it. In situations where null is really critical, we can get in your way but its frequent use will clutter entity classes. BTW for my current case your first suggestion worked like a charm.
Leslie Norman
+3  A: 

Another option that seems to work (tested on DB2, MySQL, Oracle, and SQL Server):

select id, cast(null as char), name from ...

You could subclass the Hibernate dialect and abstract it with a custom function:

registerFunction("always_null", 
  new SQLFunctionTemplate(Hibernate.STRING, "cast(null as char)"));

and then use this in your HQL:

select id, always_null(), name from ...
Brian Deterling
Interesting! Are you still getting a "real" `null` with `cast(null as char)` or are you getting a `'null'`?
Pascal Thivent
Yes, it's a real null.
Brian Deterling
@Brian Cool! In the absence of generic solution in hibernate, it saves our skin. Good thing is, we will not have to play with Java objects
Leslie Norman