3

I created an util method:

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)));
}

So if for example if User has lazy orders and wallets, I can do this:

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

But I don't know how to take orders's or wallets lazy collections. It would be greate if I would call method like this:

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

How can I extend the method to achieve this?

1 Answer 1

5

I decided to use the next method:

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)));
}

It has only one defect. The next two will work:

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

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

The next one will not:

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

That's because orders overrides orders.products. I think it's enough, because logically if you want to load orders.products, you have to load orders anyway.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.