JPA Criteria API with multiple parameters

前端 未结 5 1768
礼貌的吻别
礼貌的吻别 2020-11-30 22:39

I need to make a search method that uses the JPA Criteria API with multiple parameters. Now the problem is that not every parameter is required. So some could be null, and t

5条回答
  •  青春惊慌失措
    2020-11-30 23:13

    Take a look at this site JPA Criteria API. There are plenty of examples.

    Update: Providing a concrete example

    Let's search for Accounts with a balance lower than a specific value:

    SELECT a FROM Account a WHERE a.balance < :value
    

    First create a Criteria Builder

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    
    CriteriaQuery accountQuery = builder.createQuery(Account.class);
    Root accountRoot = accountQuery.from(Account.class);
    ParameterExpression value = builder.parameter(Double.class);
    accountQuery.select(accountRoot).where(builder.lt(accountRoot.get("balance"), value));
    

    To get the result set the parameter(s) and run the query:

    TypedQuery query = entityManager.createQuery(accountQuery);
    query.setParameter(value, 1234.5);
    List results = query.getResultList();
    

    BTW: The entityManager is injected somewhere in an EJB/Service/DAO.

提交回复
热议问题