当我有以下实体时。
@Entity
class Article {
@OneToMany
Set<Comment> comments;
}
@Entity
class Comment {
@ManyToOne
User author;
}
并使用 EntityGraph 和静态元模型创建一些视图规范类,如下所示。
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;
};
}
但是上面的类不能编译,因为预期的类型不是
Subgraph<Comment> sgComment = graph.addSubgraph(Article_.comments);
但
Subgraph<Set<Comment>> sgComment = graph.addSubgraph(Article_.comments);
当我们有扩展属性时会出现此问题javax.persistence.metamodel.PluralAttribute
。(例如 SetAttribute、ListAttribute)
这种行为显然来自 api 规范。
javax.persistence.EntityGraph#addSubgraph(javax.persistence.metamodel.Attribute<T,X>)
但是在这种情况下,如何使用 JPA 静态 MetaModel 以可编程和类型安全的方式创建 EntityGraph 呢?
解决方法
/**
* 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;
};