【问题标题】:How to achieve "not in" by using Restrictions and criteria in Hibernate?如何通过在 Hibernate 中使用限制和标准来实现“不在”?
【发布时间】:2010-11-16 07:03:23
【问题描述】:

我有类别列表。我需要排除 2,3 行的类别列表。我们可以通过使用 Criteria 和 Restriction 通过hibernate 来实现吗?

【问题讨论】:

    标签: hibernate criteria restriction


    【解决方案1】:

    您的问题有些不清楚。假设“Category”是根实体,“2,3”是 ids(或类别的某些属性的值),您可以使用以下命令排除它们:

    Criteria criteria = ...; // obtain criteria from somewhere, like session.createCriteria() 
    criteria.add(
      Restrictions.not(
         // replace "id" below with property name, depending on what you're filtering against
        Restrictions.in("id", new long[] {2, 3})
      )
    );
    

    DetachedCriteria 也可以这样做。

    【讨论】:

      【解决方案2】:
       Session session=(Session) getEntityManager().getDelegate();
              Criteria criteria=session.createCriteria(RoomMaster.class);
      //restriction used or inner restriction ...
              criteria.add(Restrictions.not(Restrictions.in("roomNumber",new String[] { "GA8", "GA7"})));
              criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
              List<RoomMaster> roomMasters=criteria.list();
      

      【讨论】:

        【解决方案3】:

        对于自 Hibernate 5.2 版本以来的新标准:

        CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
        CriteriaQuery<Comment> criteriaQuery = criteriaBuilder.createQuery(Comment.class);
        
        List<Long> ids = new ArrayList<>();
        ids.add(2L);
        ids.add(3L);
        
        Root<Comment> root = getRoot(criteriaQuery);
        Path<Object> fieldId = root.get("id");
        Predicate in = fieldId.in(ids);
        Predicate predicate = criteriaBuilder.not(in);
        
        criteriaQuery
                .select(root)
                .where(predicate);
        
        List<Comment> list = getSession()
                .createQuery(criteriaQuery)
                .getResultList();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-06-15
          • 2018-02-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多