渴望查询中的惰性关系?

时间:2019-05-09 19:06:39

标签: java jpa lazy-loading eager-loading

我有一个具有这种惰性关系的实体:

@Getter
@Entity
@Table(name = "entity")
@SequenceGenerator(name = "seq_entity", sequenceName = "seq_entity", allocationSize = 1)
@DynamicUpdate
public class Entity {

    @Id
    @Column(name = "id_entity")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_entity")
    private Long id;

    @Setter
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "id_relation1")
    private Relation1 relation1;

    @Setter
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "id_relation2")
    private Relation2 relation2;

    // ...
}

当我查询以加载其他关系时,必须像这样指定它们:

return jpaQuery() .select(qEntity) .distinct() .from(qEntity) .innerJoin(qEntity.relation1).fetchJoin() .leftJoin(qEntity.relation2).fetchJoin() .fetch();

但是我想在不指定的情况下将它们加载到一个查询的左联接和内联接中... 有一种方法可以在一个查询中以全部模式加载所有内容?是否可以为一个查询停用FetchType.LAZY

我在想类似的东西

return jpaQuery() .select(qEntity) .distinct() .from(qEntity) .fetchEager();

1 个答案:

答案 0 :(得分:3)

您可以为此使用实体图。会是这样的:

EntityGraph<Post> entityGraph = entityManager.createEntityGraph(YourEntity.class);
entityGraph.addAttributeNodes("relation1");
entityGraph.addAttributeNodes("relation2");

在查询中

TypedQuery<Post> typedQuery = entityManager.createQuery(criteriaQuery);
typedQuery.setHint("javax.persistence.loadgraph", entityGraph);
Post post = typedQuery.getSingleResult();

这可以用命名实体图(在实体上)括起来

@NamedEntityGraph(
  name = "entity-with-all-relations",
  attributeNodes = {
    @NamedAttributeNode("relation1"),
    @NamedAttributeNode("relation2"),
  },

因此多次重复使用。为此,请使用EntityManager#getEntityGraph