0
试图采取这种方法,并优化性能选择抽象服务的通用对象列表:如何使用CriteriaQuery中
public T getByPrimaryKey(PK id) {
T entity = getEntityManager().find(getEntityClass(), id);
if(entity != null) {
preProcessEntity(entity);
}
fireEvent(entity, IEntityEventService.Event.READ, null);
return entity;
}
的原因是,我们有我们得到基于本地ID列表许多领域查询,并且它们正在逐个处理,导致由Hibernate创建的单个查询。我想让Hibernate一次抓取这些。
public List<T> getEntitiesByPrimaryKey(List<PK> pks) {
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(getEntityClass());
Root<T> root = cq.from(getEntityClass());
Metamodel m = getEntityManager().getMetamodel();
EntityType<T> T_ = m.entity(getEntityClass());
Path<T> keyPath = root.get(T_.getDeclaredId(getEntityClass()));
cq.select(root);
cq.where(keyPath.in(pks));
List<T> entities = getEntityManager().createQuery(cq).getResultList();
if(entities != null) {
for (T entity : entities) {
preProcessEntity(entity);
fireEvent(entity, IEntityEventService.Event.READ, null);
}
}
return entities;
}
我不知道该从哪里出发。主键不保证是整数,但几乎肯定会是。