gpt4 book ai didi

java - JPA 动态 EntityGraph 和子图

转载 作者:行者123 更新时间:2023-11-30 07:01:41 25 4
gpt4 key购买 nike

我创建了一个 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)));
}

因此,如果用户有惰性订单钱包,我可以这样做:

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

但我不知道如何接受订单钱包惰性集合。如果我能调用这样的方法那就太好了:

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

如何扩展该方法来实现此目的?

最佳答案

我决定使用下一个方法:

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

关于java - JPA 动态 EntityGraph 和子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com