This is what worked for me (thanks @sergiu):
The following method creates the select part of the query:
public List<UserEntity> search(final String maybePartialUsername, final String maybePartialRuleName)
throws EntityException {
final String selectUsersStatement = "select distinct users from UserEntity as users";
final String joinUsersWithRulesClause = shouldFilterSearchBy(maybePartialRuleName) ? "inner join users.rules as rules" : null;
return search(Joiner.on(" ").skipNulls().join(selectUsersStatement, joinUsersWithRulesClause),
maybePartialUsername, maybePartialRuleName);
}
Which then calls a method (not shown) which calls the following to build the where parts of the query:
private String buildSearchQueryFrom(final String selectStatement, final String maybePartialUsername,
final String maybePartialRuleName) {
final Collection<String> searchFilters = Lists.newArrayListWithCapacity(2);
if (shouldFilterSearchBy(maybePartialUsername)) {
searchFilters.add("users.username like :maybePartialUsername");
}
if (shouldFilterSearchBy(maybePartialRuleName)) {
searchFilters.add("rules.ruleName like :maybePartialRuleName");
}
final String whereClauseParts = Joiner.on(" and ").skipNulls().join(searchFilters);
return Joiner.on(" where ").skipNulls().join(selectStatement, whereClauseParts);
}
And a helper method called by the method above:
protected boolean shouldFilterSearchBy(final String searchValue) {
return !Strings.isNullOrEmpty(searchValue);
}