【问题标题】:Hibernate add Restriction ( equals ) only if the parameter is not null仅当参数不为空时,休眠添加限制(等于)
【发布时间】:2019-03-26 10:38:08
【问题描述】:

如何检查参数是否为空? 根据我要添加或不添加限制的结果

如果 person.getLastName() == null 我不想添加相关限制, 我该怎么做?

    persons = session.createCriteria(PersonEntity.class).add(
                Restrictions.eq("LastName", person.getLastName())).add(
                Restrictions.eq("FirstName", person.getFirstName())).add(
                Restrictions.eq("email", person.getUser().getEmail()))
                .list();

谢谢,塔尼亚

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    你可以在一个方法中用普通的 if 来做:

    private void addRestrictionIfNotNull(Criteria criteria, String propertyName, Object value) {
        if (value != null) {
            criteria.add(Restrictions.eq(propertyName, value));
        }
    }
    

    然后使用它:

    Criteria criteria = session.createCriteria(PersonEntity.class);
    addRestrictionIfNotNull(critera, "LastName", person.getLastName());
    addRestrictionIfNotNull(critera, "FirstName", person.getFirstName());
    addRestrictionIfNotNull(critera, "email", person.getEmail());
    
    persons = criteria.list();
    

    【讨论】:

      【解决方案2】:

      你可以使用这样复杂的限制:

      Restrictions.or(Restrictions.and(Restrictions.isNotNull("propName"), Restrictions.eq("propName", propValue)), Restrictions.isNull("propName"));
      

      如果我理解你是正确的,它将达到你的预期。

      内部限制的结果Restrictions.eq("propName", propValue)只有在指定属性不为空时才会影响查询结果。

      附言。我知道这似乎太模糊了,但现在我无法想象另一种方法来做到这一点。

      【讨论】:

      • 问题是检查要匹配的给定值的无效性,而不是字段值。您的解决方案似乎不错,但它会检查数据库中“propName”字段的无效性,而在这里(根据问题),“propValue”将被检查为无效。
      • 问题是关于对象比较而不是数据库字段@param value The value to use in comparison
      【解决方案3】:

      所以,你可以这样做,

      session = sessionFactory.getCurrentSession();
      Criteria crit = session.createCriteria(PersonEntity.class).add(
                      Restrictions.eq("FirstName", person.getFirstName())).add(
                      Restrictions.eq("email", person.getUser().getEmail()));
      if(person.getLastName()!=null){
      crit.add(Restrictions.eq("LastName", person.getLastName()));
      }
      person=(PersonVO)crit.list();
      

      【讨论】:

        【解决方案4】:

        如果您的last_name 列在表格中始终是not null,您可以尝试如下操作:

        String lastName = .. ;
        
        .add(Restrictions.sqlRestriction(lastName != null ? "this_.last_name = "+ lastName : "this_.last_name is not null "))
        

        这里last_name 将是您的表列名称。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-12-13
          • 2011-07-27
          • 2023-04-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多