如何从休眠会话中删除不需要的实体?
我试图通过查询映射到它的实体来获取。我正在使用如下图来执行此操作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”上执行的,而没有在连接中指定Entity2。我的猜测是,实体 2 已经在会话中可用,并且它被懒惰地初始化为实体 1。因此,条件会生成对实体 2 而不是实体 1 的查询。
有没有办法限制在实体 1 上查询的条件?或者如何在执行此特定条件之前从会话中删除 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;
}
实体 1 和实体 2 的参考表
表名: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)