Apache Cayenne > Index > Cayenne FAQ > Expression Chaining
Added by cris, last edited by cris on May 24, 2005

When chaining expressions together, it is common to make the following mistake:

BrokenChainedExpression.java
Expression sampleExpression = 
    ExpressionFactory.matchExp(MyDataObject.FIELD1_PROPERTY, foo);

sampleExpression.andExp(ExpressionFactory.matchExp(MyDataObject.FIELD2_PROPERTY, bar));

However, this code is incorrect, as Cayenne Expressions are immutable. andExp and orExp will return a new Expression object that you must assign. The following is a correct example of chaining expressions:

ProperChainedExpression.java
Expression sampleExpression = 
    ExpressionFactory.matchExp(MyDataObject.FIELD2_PROPERTY, foo);

sampleExpression = sampleExpression.andExp(
    ExpressionFactory.matchExp(MyDataObject.FIELD1_PROPERTY, bar));

Another option for chaining is to use listExp, which chains together a List of Expression objects with the specified conjunction. This can be much cleaner when building complex queries.

ExpressionFactory.listExp(Expression.AND, expressionList)

The Expression javadocs provide additional detail on expression chaining.