| Apache Cayenne > Index > Cayenne FAQ > Not In To Many FAQ |
Sometimes there is a need to find all objects that DO NOT have a certain object (or objects) on the other side of their to-many relationship. From the SQL standpoint, an inner join will not produce the right results. Rather a subquery is normally used. In Cayenne you can do this in a simple two step process. Lets take the following example. There is a Project class and a Task class. Project has many tasks. We need to fetch all projects that do not contain a task with type "Database".
The most obvious, but incorrect solution:
DataContext ctxt; ... Expression qualifier = ExpressionFactory.noMatchExp("taskArray.type", "Database"); List projects = ctxt.performQuery(new SelectQuery(Project.class, qualifier));
Correct solution:
DataContext ctxt; ... Expression qualifier = ExpressionFactory.matchExp("taskArray.type", "Database"); List excludeProjects = ctxt.performQuery(new SelectQuery(Project.class, qualifier)); List projects = ctxt.performQuery(new SelectQuery(Project.class)); // filter out projects that do not satisfy criteria projects.removeAll(excludeProjects);