Hibernate Criteria Builder IN子句查询

时间:2018-10-29 04:56:57

标签: java hibernate jpa hibernate-criteria

如何在Hibernate中为以下给定查询编写条件构建器api查询? batchId不是主键,也不是唯一的。

  

SELECT * FROM User WHERE batchID IN('1','3')

我尝试过:

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<User> criteriaQuery = builder.createQuery(User.class);
    Root<User> userRoot = criteriaQuery.from(User.class);

    List<Integer> batchIdList = new ArrayList<>();
    batchIdList.add(1);
    batchIdList.add(3);

    Predicate queryPredicate = builder.in(userRoot.get(User_.batchId).in(batchIdList)); 

    criteriaQuery.select(userRoot);
    criteriaQuery.where(queryPredicate);

    TypedQuery<User> userQuery = entityManager.createQuery(criteriaQuery);

    List<User> userResult = userQuery.getResultList();

除了数据库中存在数据外,我什么也没得到。

2 个答案:

答案 0 :(得分:2)

使用它。我假设您的batchId为Integer

 CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<User> criteriaQuery = builder.createQuery(User.class);
        Root<User> userRoot = criteriaQuery.from(User.class);
         criteriaQuery.select(userRoot);    

        List<Integer> batchIdList = new ArrayList<>();
        batchIdList.add(1);
        batchIdList.add(3);
        criteriaQuery            
  .where(builder.and(userRoot.get(User_.batchId).in(batchIdList)));
        TypedQuery<User> userQuery = entityManager.createQuery(criteriaQuery);

        List<User> userResult = userQuery.getResultList();

答案 1 :(得分:0)

Hiberbate 5.3及更高版本的条件查询中IN子句的工作示例。

在下面的示例中,找到名称分别为(sumit,amit,vivek)和24岁的员工数据。

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;


public void getCriteria() {

        Session session = null;
        try {
            session = getSessionfactory().openSession();
            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Employee> criteria = builder.createQuery(Employee.class);
            Root<Employee> root = criteria.from(Employee.class);
            List<Predicate> predicates = new ArrayList<Predicate>();
            predicates.add(builder.in(root.get("name")).value("sumit").value("amit").value("vivek"));   // IN clause
            predicates.add(builder.equal(root.get("age"),24));
            criteria.select(root).where(predicates.toArray(new Predicate[] {}));
            List<Employee> employeeList = session.createQuery(criteria).getResultList();
        }
        catch(Exception e) {
            System.out.println(e);
        }

    }