|
| 1 | +package io.objectbox.relation; |
| 2 | + |
| 3 | +import io.objectbox.query.Query; |
| 4 | +import io.objectbox.query.QueryBuilder; |
| 5 | +import org.junit.Test; |
| 6 | + |
| 7 | +import static org.junit.Assert.assertEquals; |
| 8 | +import static org.junit.Assert.assertNotNull; |
| 9 | + |
| 10 | +/** |
| 11 | + * Tests link conditions for queries to filter on related entities. |
| 12 | + * <p> |
| 13 | + * There are more extensive tests in integration tests. |
| 14 | + */ |
| 15 | +public class LinkQueryTest extends AbstractRelationTest { |
| 16 | + |
| 17 | + @Test |
| 18 | + public void link_withRegularCondition() { |
| 19 | + Customer john = putCustomer("John"); |
| 20 | + putOrder(john, "Apples"); |
| 21 | + putOrder(john, "Oranges"); |
| 22 | + |
| 23 | + Customer alice = putCustomer("Alice"); |
| 24 | + putOrder(alice, "Apples"); |
| 25 | + putOrder(alice, "Bananas"); |
| 26 | + |
| 27 | + // link condition matches orders from Alice |
| 28 | + // simple regular condition matches single order for both |
| 29 | + QueryBuilder<Order> builder = orderBox |
| 30 | + .query(Order_.text.equal("Apples")); |
| 31 | + builder.link(Order_.customer) |
| 32 | + .apply(Customer_.name.equal("Alice").alias("name")); |
| 33 | + |
| 34 | + try (Query<Order> query = builder.build()) { |
| 35 | + Order order = query.findUnique(); |
| 36 | + assertNotNull(order); |
| 37 | + assertEquals("Apples", order.getText()); |
| 38 | + assertEquals("Alice", order.getCustomer().getTarget().getName()); |
| 39 | + } |
| 40 | + |
| 41 | + // link condition matches orders from Alice |
| 42 | + // complex regular conditions matches two orders for John, one for Alice |
| 43 | + QueryBuilder<Order> builderComplex = orderBox |
| 44 | + .query(Order_.text.equal("Apples").or(Order_.text.equal("Oranges"))); |
| 45 | + builderComplex.link(Order_.customer) |
| 46 | + .apply(Customer_.name.equal("Alice")); |
| 47 | + |
| 48 | + try (Query<Order> query = builderComplex.build()) { |
| 49 | + Order order = query.findUnique(); |
| 50 | + assertNotNull(order); |
| 51 | + assertEquals("Apples", order.getText()); |
| 52 | + assertEquals("Alice", order.getCustomer().getTarget().getName()); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | +} |
0 commit comments