JPA EntityGraph, create subgraph of PluralAttribute programmably by using static MetaModel

Viewed 1116

When I have below entity.

@Entity
class Article {
  @OneToMany
  Set<Comment> comments;
}

@Entity
class Comment {
  @ManyToOne
  User author;
}

And create some view specification class using EntityGraph and static metamodel like below.

class ArticleViewSpec {

  /**
   * fetch comments and each of comment's author.
   */
  public static final Function<EntityManager, EntityGraph<Article>> DETAIL = em -> {
    EntityGraph<Article> graph = em.createEntityGraph(Article.class);

    Subgraph<Comment> sgComment = graph.addSubgraph(Article_.comments);

    sgComment.addAttributeNodes(Comment_.author);

    return graph;
  };
}

But above class can't be compiled, because expected type is not

Subgraph<Comment> sgComment = graph.addSubgraph(Article_.comments);

but

Subgraph<Set<Comment>> sgComment = graph.addSubgraph(Article_.comments);

This problem occurs when we have attribute that extends javax.persistence.metamodel.PluralAttribute. (e.g. SetAttribute, ListAttribute)

This behaviour is obviously from api spec. javax.persistence.EntityGraph#addSubgraph(javax.persistence.metamodel.Attribute<T,X>)

But how can I create EntityGraph programmably and type-safely using JPA static MetaModel in these case ?

Workaround

/**
 * fetch comments and each of comment's author.
 */
public static final Function<EntityManager, EntityGraph<Article>> DETAIL = em -> {
    EntityGraph<Article> graph = em.createEntityGraph(Article.class);

    Subgraph<Comment> sgComment =
      graph.addSubgraph(Article_.comments.getName(), Comment.class);

    sgComment.addAttributeNodes(Comment_.author);

    return graph;
  };
1 Answers
Related