Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[eclipselink-users] Search using Expression API - Is there an easier way?

I am starting to play with the expression API more, and it seems a bit
clunky to me. Perhaps I'm just dense, but the issue seems to be the
need to logically join each condition.

This gets really messy when you're trying to do a generic search in a
web app - there are 20 fields, each field they enter a value on should
be anded with any other fields present. This is a pretty common
pattern.

I was hoping I would be able to have the expression built
automatically perhaps with a default logical condition somehow. I
could probably build something in a half hour that did that, but it
seems like this functionality should exist somewhere already. How are
other people dealing with this common pattern?

Here's what I came up with, as the simplest solution, am I missing
something? It's tedious with all the null checking, etc.

	private Expression getSearchExpression(MyFruit fruit)
	{
		Expression eb = new ExpressionBuilder();
		Expression color = null,taste = null,smell = null;
		if(!example.getColor().isEmpty())
			color = eb.get("color").equal(example.getColor());
		
		if(!example.getTaste().isEmpty())
			taste  = eb.get("taste").equal(example.getTaste());
		
		if(!example.getSmell().isEmpty())
			smell = eb.get("smell").equal(example.getSmell());

		return andConditions(color,taste,smell);
	}


	private Expression andConditions(Expression...exps)
	{
		if(exps ==  null)
			return null;
		
		if(exps.length == 1)
			return exps[0];
		
		Expression e = null;
		boolean initExp = false;
		for (Expression tmpE : exps) {
			if(tmpE != null)
			{
				if(!initExp)
				{
					e = tmpE;
					initExp = true;
				}
				else
				{
					e = e.and(tmpE);
				}
			}
		}
		return e;
	}


./tch


Back to the top