【发布时间】: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