【问题标题】:how to convert following sql query using criteria api?如何使用条件 api 转换以下 sql 查询?
【发布时间】:2019-06-17 15:58:19
【问题描述】:

我有一个查询,它已经写在扩展 JpaRepository 的存储库中。但我需要在这里添加逻辑运算符。

select ac from Accounts ac where ac.userId = :userId and ac.accountId = :accountID

当客户端提供 userId 或 accountId 时,要求获取帐户详细信息。

public interface GoalPlanRepository extends JpaRepository<GoalPlan, String>{

    @Query("select ac from Accounts ac where ac.userId = :accountID ")
    public List<Accounts> getCalculateRecurringAmount(@Param("accountID") String accountID, @Param("userId") String userId);

这是我的存储库。我在goalPlanDaoImplementation中实现这个方法

    public List<Accounts> getCalculateRecurringAmount(String accountID) {


    //      CriteriaBuilder cb = em.getCriteriaBuilder();
    //        CriteriaQuery<Accounts> cq = cb.createQuery(Accounts.class);
    // 
    //        Root<Accounts> acc = cq.from(Accounts.class);
    //        
    //        Predicate accountIDPredicate = null;
    //        Predicate userIdPredicate = null;
    //        
    //        if(accountID != null) {
    //        accountIDPredicate = cb.equal(acc.get("accountID"), accountID);
    //        }
    //        
    //        if(userId != null) {
    //        userIdPredicate = cb.equal(acc.get("userId"), userId);
    //        }
    //        
    //       
    //        cq.where(accountIDPredicate, userIdPredicate);
    //        
    //        TypedQuery<Accounts> query = em.createQuery(cq);

              List<Accounts> goalPlan = null;
              goalPlan = goalPlanRepository.getCalculateRecurringAmount(accountID);
               return goalPlan;
            //return query.getResultList();




        }

评论部分是我尝试做的。提前致谢。 :)

【问题讨论】:

    标签: java jpa spring-data-jpa criteria-api


    【解决方案1】:

    我不确定我的理解是否正确,但也许这会有所帮助:

    final ArrayList<Predicate> predicates = new ArrayList<Predicate>();
    if(accountID != null) 
        predicates.add(cb.equal(acc.get("accountID"), accountID));
    }
    if(userId != null) {
        predicates.add(cb.equal(acc.get("userId"), userId));
    }
    
    switch(predicates.size()){
    case 0:
        return null;
        //or maybe just continue to return all accounts...
    case 1:
        cq.where(predicates.get(0));
        break;
    default:
        cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-01
      • 1970-01-01
      • 2021-05-19
      • 2016-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-29
      • 2016-01-06
      相关资源
      最近更新 更多