Giancarlo Sanchez
Giancarlo Sanchez

Reputation: 207

Java Criteria API Like condition

I need to build a dynamic query (with optional filtering parameters and conditions) in Java. I decided to go for the Criteria API since it seemed the most flexible approach.

An example of the condition I'm trying to achieve (Mysql perspective):

WHERE idClient = X AND ( idChannel = 1 OR idChannel = 2 OR idChannel = 25) AND filter LIKE '%test%'

The parameter "criteria" is a List of predicates with the idChannel filters, created as follows:

//Filter by channel
for (Channel channel : channels){
   Predicate channelFilter = qb.equal(address.get(AddressBlocked_.idChannel), channel);
   criteria.add(channelFilter);
}

The condition I wrote using the Criteria API (Java perspective):

Predicate predicate = qb.and(
      //Client filter
      qb.equal(address.get(AddressBlocked_.idClient), idClient),

      //Channel filter
      qb.or(
            criteria.toArray(new Predicate[criteria.size()])
      ),

      //Address filter
      qb.like(address.get(AddressBlocked_.address), "%"+search+"%") 
);

Whenever the address filter "search" variable has any value, the list returns null, otherwise the filtering by channels and client works perfect.

I haven't been able to implement a LIKE filtering option in my CriteriaQuery. Any other approach I should be using or tip?

Upvotes: 2

Views: 3083

Answers (1)

Arthur Dent
Arthur Dent

Reputation: 795

Perhaps try using an asterisk for your wildcard character as in the following:

http://docs.oracle.com/javaee/6/tutorial/doc/gjivm.html

Upvotes: 2

Related Questions