猿问

JPA 标准产生一个只有一个问题点的查询

在我们的数据库中,我们有缓存系统,它对查询绑定参数敏感。


我有以下查询创建:


@Override

public Predicate toPredicate(Root<Position> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {

    query.distinct(true);

    final Collection<Predicate> predicates = new ArrayList<>();


    Join<Position, ManagersPositions> managersPositionsJoin = root.join("managersPositions", JoinType.INNER);


    Predicate managerPredicate = criteriaBuilder.equal(managersPositionsJoin.get("managerId"), managerId);

    predicates.add(managerPredicate);


    if (onlyDirect) {

        Predicate equalsDirect = criteriaBuilder.equal(managersPositionsJoin.get("isDirect"), true);

        predicates.add(equalsDirect);

    }

    return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));

}

它产生以下查询:


select

   distinct position0_.id as id1_69_0_,

   ...

where managerspo1_.manager_id=22

and managerspo1_.is_direct=?

我必须发送带有 2 个绑定参数的请求,例如:


where managerspo1_.manager_id=?

and managerspo1_.is_direct=?

如何解决第一个“?”的问题?


慕容森
浏览 263回答 2
2回答

牛魔王的故事

我还没有找到解决问题的方法,我的决定是在没有规范的情况下使用实体管理器“手动创建”查询。final String queryString = "select distinct pos from Position pos " +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "inner join pos.managersPositions mn " +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "where mn.managerId = :managerId and mn.isDirect = :isDirect ";&nbsp; &nbsp; TypedQuery<Position> query = entityManager.createQuery(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; queryString,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Position.class);&nbsp; &nbsp; query.setParameter("managerId", managerEmployeeId);&nbsp; &nbsp; query.setParameter("isDirect", true);因为当我制作它时criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));,它只制作了一个带有一个参数的谓词。还尝试将规格分为 2,结果不成功:Specification.where(firstSpecification).and(secondSpecification)

吃鸡游戏

使用 CriteriaBuilder.parameter() 添加多个参数:&nbsp; &nbsp; ParameterExpression<Integer> managerIdParam =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; criteriaBuilder.parameter( Integer.class );&nbsp; &nbsp; ParameterExpression<Boolean> isDirectParam =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; criteriaBuilder.parameter( Boolean.class );&nbsp; &nbsp; Predicate managerPredicate =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; criteriaBuilder.equal(managersPositionsJoin.get("managerId"),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; managerIdParam);&nbsp; &nbsp; Predicate equalsDirect =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; criteriaBuilder.equal(managersPositionsJoin.get("isDirect"), isDirectParam);
随时随地看视频慕课网APP

相关分类

Java
我要回答