【问题标题】:Hibernate generate unnecessary cross join and duplicate resultsHibernate 生成不必要的交叉连接和重复结果
【发布时间】:2022-01-26 23:00:06
【问题描述】:

我需要用spring data jpa和criteria api编写一个动态查询,但是hibernate会产生不必要的交叉连接和重复的结果。

实体类

@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 = ?

为什么会这样?

【问题讨论】:

  • 请输入样本数据和想要的输出
  • 表包含3条记录,结果(计数)输出:9(每个条目被选中3次)
  • 为什么要使用交叉连接?无法通过简单的选择来回答?
  • 我只使用select count,但是hibernate生成交叉连接

标签: java sql postgresql hibernate spring-data-jpa


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-02-25
    • 2014-11-19
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 2013-05-06
    • 2015-10-18
    • 2021-11-08
    相关资源
    最近更新 更多