JPA动态EntityGraph和Subgraphs

时间:2016-11-25 02:47:13

标签: java jpa

我创建了一个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有懒惰的orderswallets,我可以这样做:

Optional<User> user = fetch(User.class, 1, "orders", "wallets");

但我不知道如何使用orderswallets懒惰的集合。如果我打电话给这样的方法会很重要:

Optional<User> user = fetch(User.class, 1, "orders", "orders.products", "wallet");

如何扩展方法来实现这一目标?

1 个答案:

答案 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