我创建了一个util方法:
public <T> Optional<T> fetch(Class<T> clazz, Object id, String... relations) {
EntityGraph<T> graph = entityManager.createEntityGraph(clazz);
Stream.of(relations).forEach(graph::addSubgraph);
return Optional.ofNullable(entityManager.find(clazz, id, Collections.singletonMap("javax.persistence.loadgraph", graph)));
}
因此,如果User
有懒惰的orders
和wallets
,我可以这样做:
Optional<User> user = fetch(User.class, 1, "orders", "wallets");
但我不知道如何使用orders
或wallets
懒惰的集合。如果我打电话给这样的方法会很重要:
Optional<User> user = fetch(User.class, 1, "orders", "orders.products", "wallet");
如何扩展方法来实现这一目标?
答案 0 :(得分:0)
我决定使用下一个方法:
public <T> Optional<T> fetch(Class<T> clazz, Object id, String... relations) {
EntityGraph<T> graph = entityManager.createEntityGraph(clazz);
Stream.of(relations).forEach(path -> {
String[] splitted = path.split("\\.");
Subgraph<T> root = graph.addSubgraph(splitted[0]);
for (int i = 1; i < splitted.length; i++)
root = root.addSubgraph(splitted[i]);
});
return Optional.ofNullable(entityManager.find(clazz, id, Collections.singletonMap("javax.persistence.loadgraph", graph)));
}
它只有一个缺陷。接下来的两个将起作用:
Optional<User> user = fetch(User.class, 1, "orders", "orders.products", "wallet");
Optional<User> user = fetch(User.class, 1, "orders.products", "wallet");
下一个不会:
Optional<User> user = fetch(User.class, 1, "orders.products", "orders", "wallet");
那是因为orders
会覆盖orders.products
。我认为这已经足够了,因为从逻辑上讲,如果你想加载orders.products
,你必须加载orders
。