|
| 1 | +--- |
| 2 | +layout: default |
| 3 | +title: Alias Usage |
| 4 | +parent: Guides |
| 5 | +nav_order: 4 |
| 6 | +--- |
| 7 | + |
| 8 | +# Alias Usage |
| 9 | + |
| 10 | +In cases where code generation is not an option, alias objects can be used as |
| 11 | +path references for expression construction. They work via proxied Java Bean |
| 12 | +objects through getter method invocations. |
| 13 | + |
| 14 | +The following examples demonstrate how alias objects can be used as |
| 15 | +replacements for expression creation based on generated types. |
| 16 | + |
| 17 | +First, an example query with APT-generated domain types: |
| 18 | + |
| 19 | +```java |
| 20 | +QCat cat = new QCat("cat"); |
| 21 | +for (String name : queryFactory.select(cat.name).from(cat,cats) |
| 22 | + .where(cat.kittens.size().gt(0)) |
| 23 | + .fetch()) { |
| 24 | + System.out.println(name); |
| 25 | +} |
| 26 | +``` |
| 27 | + |
| 28 | +And now with an alias instance for the `Cat` class. The call |
| 29 | +`c.getKittens()` inside the dollar-method is internally transformed into the |
| 30 | +property path `c.kittens`. |
| 31 | + |
| 32 | +```java |
| 33 | +Cat c = alias(Cat.class, "cat"); |
| 34 | +for (String name : select($(c.getName())).from($(c),cats) |
| 35 | + .where($(c.getKittens()).size().gt(0)) |
| 36 | + .fetch()) { |
| 37 | + System.out.println(name); |
| 38 | +} |
| 39 | +``` |
| 40 | + |
| 41 | +To use the alias functionality, add the following two imports: |
| 42 | + |
| 43 | +```java |
| 44 | +import static com.querydsl.core.alias.Alias.$; |
| 45 | +import static com.querydsl.core.alias.Alias.alias; |
| 46 | +``` |
| 47 | + |
| 48 | +The following example is a variation where the access to the list size happens |
| 49 | +inside the dollar-method invocation: |
| 50 | + |
| 51 | +```java |
| 52 | +Cat c = alias(Cat.class, "cat"); |
| 53 | +for (String name : queryFactory.select($(c.getName())).from($(c),cats) |
| 54 | + .where($(c.getKittens().size()).gt(0)) |
| 55 | + .fetch()) { |
| 56 | + System.out.println(name); |
| 57 | +} |
| 58 | +``` |
| 59 | + |
| 60 | +All non-primitive and non-final typed properties of aliases are aliases |
| 61 | +themselves. You may cascade method calls until you hit a primitive or final |
| 62 | +type in the dollar-method scope, e.g.: |
| 63 | + |
| 64 | +```java |
| 65 | +$(c.getMate().getName()) |
| 66 | +``` |
| 67 | + |
| 68 | +is transformed into `c.mate.name` internally, but: |
| 69 | + |
| 70 | +```java |
| 71 | +$(c.getMate().getName().toLowerCase()) |
| 72 | +``` |
| 73 | + |
| 74 | +is not transformed properly, since the `toLowerCase()` invocation is not |
| 75 | +tracked. |
| 76 | + |
| 77 | +You may only invoke getters, `size()`, `contains(Object)`, and `get(int)` on |
| 78 | +alias types. All other invocations throw exceptions. |
0 commit comments