问题
I have a query which is already written in a Repository extending JpaRepository. But I need to add logical operator here.
select ac from Accounts ac where ac.userId = :userId and ac.accountId = :accountID
Requirement is getting account details when either userId or accountId is provided by the client.
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);
This is My repository. I am implementing this method in 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();
}
commented section is what I tried doing. Thanks in advance. :)
回答1:
I'm not completly sure if I understood you correct, but maybe this will help:
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()])));
}
来源:https://stackoverflow.com/questions/56634960/how-to-convert-following-sql-query-using-criteria-api