我正在使用JPA 2.1和Hibernate 5.3.3。 我有以下具有为GeoObject定义的NamedEntityGraph的实体。
select b.id, b.name, b."group", max(f.date)
from (SELECT * FROM buzz bz WHERE bz."group" in [ARRAY] and bz.name in [ARRAY]) b,
JOIN (SELECT * FROM foo WHERE date < NOW()) f ON b.id = f.buzz_id
group by b.id;
要获取所有GeoObject的列表,请进行以下查询:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@NamedEntityGraph(
name = "graph.GeoObject",
attributeNodes = { @NamedAttributeNode(value = "histogram")},
subclassSubgraphs = {
@NamedSubgraph(name = "subgraph.A", type = A.class, attributeNodes = { @NamedAttributeNode(value = "pictures") }),
@NamedSubgraph(name = "subgraph.B", type = B.class, attributeNodes = { @NamedAttributeNode(value = "artifacts") })
}
)
public abstract class GeoObject extends ObjectBase {
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name="id", updatable = false, insertable = false)
private Set<HistogramEntry> histogram = new HashSet<>();
...
}
@Entity
public class A extends GeoObject {
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
@JoinTable(joinColumns=@JoinColumn(name="a_id"), inverseJoinColumns=@JoinColumn(name="image_id"))
private Set<Image> pictures = new HashSet<>();
...
}
@Entity
public class B extends GeoObject {
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
@JoinColumn(name = "b_id", updatable = false)
private Set<Artifact> artifacts = new HashSet<>();
...
}
所有GeoObject均按预期(包括直方图属性)加载到一个SQL查询中。但是对于从A设置的图片以及从B设置的伪影,将为每个对象生成单独的查询。有没有办法构造一个EntityGraph来对所有对象进行单个查询?
顺便说一句,当我尝试动态定义EntityGraph时,像这样:
final EntityManager em = getEntityManager();
final CriteriaQuery<GeoObject> query = em.getCriteriaBuilder().createQuery(GeoObject.class);
final Root<GeoObject> entityRoot = query.from(GeoObject.class);
final EntityGraph<?> objGraph = em.getEntityGraph("graph.GeoObject");
final String hint = "javax.persistence.fetchgraph";
final List<GeoObject> result = new ArrayList<>(em.createQuery(query.distinct(true)).setHint(hint, objGraph).getResultList());
在addSubclassSubgraph中收到NotYetImplementedException。