-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: conditional where clause: CASE WHEN or Criteria
PostPosted: Fri Mar 21, 2008 10:50 am 
Beginner
Beginner

Joined: Thu May 17, 2007 8:37 am
Posts: 22
Location: London
I have a varchar field in a table called REF that is nullable. I want to be able to search on this field using LIKE. eg:
Code:
select b from Bean b where b.ref like :filter

Where "filter" is my input concatenated with '%'. eg: 'abc%'.

The problem is that if REF is null then LIKE will not find it. I could change the query to:
Code:
select b from Bean b where b.ref like :filter
or b.ref IS NULL

but then I will get *all* null results and those starting with 'abc'.

What I need is a conditional where clause. I've tried to use the CASE WHEN expression to handle this but I don't think that it is designed for this task.

For example it would have to do something like this:
Code:
select b from Bean b where b.ref
CASE WHEN :filter IS NULL
THEN like = '%' or b.ref is null
ELSE like concat(:filter, '%')
END

But of course that doesn't make any sense as you can't use the CASE in that location (it wants to be in the place of a value after the 'like').

Is there a workable solution around this or should I rewrite my queries (quite a few nasty ones) using the Criteria API?

Many thanks,

Damian


Top
 Profile  
 
 Post subject:
PostPosted: Thu May 08, 2008 10:22 am 
Beginner
Beginner

Joined: Thu May 17, 2007 8:37 am
Posts: 22
Location: London
A friend suggested a blindingly simple solution to this.

Code:
select b from Bean b
where ((:filter is not null and b.ref like :filter)
or :filter is null)

Cheers,

Damian


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.