Hibernate 生成不必要的交叉连接和重复结果

Hibernate generate unnecessary cross join and duplicate results

我需要使用 spring 数据 jpa 和条件 api 编写动态查询,但 hibernate 生成不必要的交叉连接和重复结果。

实体class

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
private String id;
private String accountId;
@CreationTimestamp
private LocalDateTime createdTs;
@UpdateTimestamp
private LocalDateTime updatedTs;

查询:

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> query = cb.createQuery(Long.class);
    Root<FavouriteItemEntity> root = query.from(MyEntity.class);

    Path<String> accountIdPath = root.get("accountId");
    List<Predicate> predicates = new ArrayList<>();
    predicates.add(cb.equal(accountIdPath, accountId));
    query.select(cb.count(query.from(MyEntity.class)));
    query.where(predicates.toArray(new Predicate[0]));
    return entityManager.createQuery(query)
            .getSingleResult();

Hql 生成交叉连接和重复结果

Hibernate: select count(favouritei1_.id) as col_0_0_ from favourite favouritei0_ cross join favourite favouritei1_ where favouritei0_.account_id=?

而不是

Hibernate: select count(f.id) from favourite f where f.account_id = ?

为什么会这样?

这是使用条件查询时的常见错误。您调用 query.from 两次,因此是交叉连接。改为调用一次:

query.select(cb.count(root));