3.4. Alias usage

In cases where code generation is not an option, alias objects can be used as path references for expression construction. They can be used via proxied Java Bean objects through getter method invocations.

The following examples demonstrate how alias objects can be used as replacements for expression creation based on generated types.

At first an example query with APT generated domain types:

QCat cat = new QCat("cat");
for (String name : query.from(cat,cats)
    .where(cat.kittens.size().gt(0))
    .list(cat.name)){
    System.out.println(name);
}

And now with an alias instance for the Cat class. The call c.getKittens() inside the dollar-method is internally transformed into the property path c.kittens.

Cat c = alias(Cat.class, "cat");
for (String name : query.from($(c),cats)
    .where($(c.getKittens()).size().gt(0))
    .list($(c.getName()))){
    System.out.println(name);
}

To use the alias functionality in your code, add the following two imports

import static com.mysema.query.alias.Alias.$;
import static com.mysema.query.alias.Alias.alias;

The following example is a variation of the previous, where the access to the list size happens inside the dollar-method invocation.

Cat c = alias(Cat.class, "cat");
for (String name : query.from($(c),cats)
    .where($(c.getKittens().size()).gt(0))
    .list($(c.getName()))){
    System.out.println(name);
}

All non-primitive and non-final typed properties of aliases are aliases themselves. So you may cascade method calls until you hit a primitive or final type in the dollar-method scope. e.g.

$(c.getMate().getName())

is transformed into *c.mate.name* internally, but

$(c.getMate().getName().toLowerCase())

is not transformed properly, since the toLowerCase() invocation is not tracked.

Note also that you may only invoke getters, size(), contains(Object) and get(int) on alias types. All other invocations throw exceptions.