我试图Entity1通过查询映射到它的实体来获取。我正在使用CriteriaBuilder执行此操作,如下所示
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Entity1> createQuery = criteriaBuilder.createQuery(Entity1.class);
Root<Entity1> root = createQuery.from(Entity1.class);
Join<Entity1, MappedEntity2> mappedEntity2Join = root.join("mappedEntity2");
createQuery.select(root);
predicate = criteriaBuilder.and(predicate, criteriaBuilder.equal(root.get(COL_USER_ID), userId));
// where clause to filter by query params
createQuery.where(predicate).distinct(true);
createQuery.getRestriction();
TypedQuery<Entity1> query = entityManager.createQuery(createQuery);
但是在随机情况下,我发现查询是在“Entity2.entities1”上执行的,而没有在join中指定Entity2。我的猜测是 Entity2 已经在会话中可用,并且它是用 entity1 延迟初始化的。因此,Criteria 会为 Entity2 而不是 Entity1 生成查询。
有什么方法可以限制在 Entity1 上查询的条件?或如何在执行此特定条件之前从会话中删除 Entity2。
预期查询,
select *
from Entity1 obj1_
inner join mappedEntity1 mObj_ on obj1_.obj_id=mObj_.id
where obj1_.id=?
但查询生成为,
select *
from entities1_entities2 obj0_
inner join Entity1 obj1_ on obj0_.obj_id=obj1_.id
where obj0_.entity2_id=?
实体结构:
public class Entity1 {
@ManyToOne
MappedEntity1 mappedEntity1;
@OneToMany
MappedEntity2 mappedEntity2;
@OneToMany
MappedEntity3 mappedEntity3;
}
和
public class Entity2 {
@OneToMany
List<Entity1> entities1;
@OneToOne
MappedEntity2 mappedEntity2;
}
Entity1 和 Entity2 的参考表
表名:entities1_entities2
entity1_id INTEGER NOT NULL,
entity2_id INTEGER NOT NULL,
CONSTRAINT entities1_entities2_entity1_id_fkey FOREIGN KEY (entity1_id)
REFERENCES entity1 (id),
CONSTRAINT entities1_entities2_entity2_id_fkey FOREIGN KEY (entity2_id)
REFERENCES entity2 (id)
富国沪深
慕桂英546537
一只萌萌小番薯
相关分类