惰性关系中的急切查询?
Eager query in a lazy relation?
我有一个具有这样惰性关系的实体:
@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();
您可以为此使用实体图。它将是这样的:
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
我有一个具有这样惰性关系的实体:
@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();
您可以为此使用实体图。它将是这样的:
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