将EntityGraph与基类和嵌入属性一起使用



由于已知的n+1问题,我想使用EntityGraph功能。我有以下实体结构:

@Entity
@Table(name = "customer")
public class Customer extends Person {
@Column(name = "foo")
public String foo;
@Column(name = "bar")
public String bar;
}
@Entity
@Table(name = "person")
public class Person {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "car.id")
public Car car;
@Embedded
public Key key;
}

@Entity
@Table(name = "car")
public class Car {
@Column(name = "a")
public String a;
@Column(name = "b")
public String b;
}
@Embeddable
public class Key
{
@Column(name = "key_id")
public Long keyId;
@Column(name = "key_color")
public String keyColor;
}

现在我想使用NamedEntityGraph。据我所知@NamedEntityGraph(name="getCustomer",includeAllAttributes=true(;它应该行得通,但不行。

使用的NamedEntityGraph调用

em.createQuery(criteriaQuery).setHint("javax.persistence.fetchgraph", em.getEntityGraph("getCustomer")).getResultList()

返回数据库中的客户数量,但包括car和Embedded Attribute键在内的所有Attributes始终为null。

我必须使用子图吗?我试图在Customer类和Person类上声明NamedEntityGraph。这没什么区别。

编辑:在与这个问题斗争了很长时间之后,我试图用这两个实体将其分解到最低级别

@Entity
@Table(name = "publication")
@NamedEntityGraph(name = "graph.Publication.articles",
attributeNodes = @NamedAttributeNode("articles"))
public class Publication {
@Id
private String publicationId;
private String name;
private String category;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "publicationId")
private List<Article> articles;
@Entity
@Table(name = "article")
public class Article {
@Id
private String articleId;
private String title;
private String publicationId;
}

如果我创建了一个查询,我可以在postgres日志中看到更多的查询。

EntityGraph<?> entityGraph = em.getEntityGraph("graph.Publication.articles");
List resultList = em.createQuery("SELECT x FROM Publication x").setHint("javax.persistence.fetchgraph", entityGraph).getResultList();

针对所有出版物的不同查询

SELECT ARTICLEID, publicationId, TITLE FROM article WHERE (publicationId = $1) parameters: $1 = 'publication_1'
SELECT ARTICLEID, publicationId, TITLE FROM article WHERE (publicationId = $1) parameters: $1 = 'publication_2'

但我只希望有一个带有联接的查询。

终于找到了解决问题的方法。我指的是我问题中经过编辑的部分。

我发现这个页面非常好地描述了如何使用批处理查询提示来提高性能。http://java-persistence-performance.blogspot.com/2010/08/batch-fetching-optimizing-object-graph.html?m=1

以我为例,我不再需要实体图了。查询应该像这样创建

List resultList = em.createQuery("SELECT x FROM Publication x").setHint("eclipselink.batch", "x.articles").getResultList();

最新更新