// 'to' is optional if only one relation matches @Backlink(to = "customer") public ToMany<Order> orders;
}
// Order.java @Entity publicclassOrder {
@Idpubliclong id;
public ToOne<Customer> customer;
}
Customercustomer=newCustomer(); customer.orders.add(newOrder()); customer.orders.add(newOrder()); longcustomerId= boxStore.boxFor(Customer.class).put(customer); // puts customer and orders
Customercustomer= boxStore.boxFor(Customer.class).get(customerId); for (Order order : customer.orders) { // TODO }
Orderorder= customer.orders.remove(0); boxStore.boxFor(Customer.class).put(customer); // optional: also remove the order from its box // boxStore.boxFor(Order.class).remove(order);
// update a related entity using its box OrderorderToUpdate= customer.orders.get(0); orderToUpdate.text = "Revised description"; // DOES NOT WORK // boxStore.boxFor(Customer.class).put(customer); // WORKS boxStore.boxFor(Order.class).put(orderToUpdate);
Orderorder=newOrder(); // new entity orderBox.attach(order); // need to attach box first order.customer.setAndPutTarget(customer);
如果目标 entity 使用自定义 IDs,必须在更新 ToOne 关联时存储它
1 2 3 4
customer.id = 12; // self-assigned id customerBox.put(customer); // need to put customer first order.customer.setTarget(customer); // or order.customer.setCustomerId(customer.getId()); orderBox.put(order);
customer.id = 12; // self-assigned id customerBox.attach(customer); // need to attach box first customer.orders.add(order); customerBox.put(customer);
如果 entity 是自定义 IDs,那么需要先存入该 entity,然后再更新关联并存储 own entity.
1 2 3 4
order.id = 42; // self-assigned id orderBox.put(order); // need to put order first customer.orders.add(order); customerBox.put(customer); // put customer, add relation to order
树形关联
可以使用 ToOne,ToMany 处理指向自身的树形关联
1 2 3 4 5 6 7 8 9
@Entity publicclassTreeNode { @Idlong id;
ToOne<TreeNode> parent;
@BackLink ToMany<TreeNode> children; }
生成的 entity 可以获取它的 parent 和 children
1 2
TreeNodeparent= entity.parent.getTarget(); List<TreeNode> children = entity.children;