【问题标题】:Filter the records through hibernate criteria通过休眠条件过滤记录
【发布时间】:2016-07-01 08:40:21
【问题描述】:

我在我的应用程序中使用了 8 种不同的字段过滤器,这些过滤器是从八个不同的下拉列表中选择的,现在我希望根据下拉选择的值获取数据。现在,如果我从下拉列表中选择了一个值,那么它将获取根据所选值的数据,其余字段为空,如果我选择另一个字段,则它将检查两个字段值,其余字段为空,它将从数据库中获取结果。这样做我有进行了一次查询以获取

的数据
public List<Companies> getFilteredData(int start,
                                int length,
                                String companyName,
                                String state,
                                Integer empId,
                                String country,
                                String website,
                                Integer pTech,
                                Integer sTech,
                                Integer status){


Criteria cr=factory.getCurrentSession().createCriteria(Companies.class);
cr.createAlias("primTech","primTech");
cr.createAlias("secondTech","secondTech");
cr.createAlias("statuss","statuss");
cr.createAlias("employee","employee");

cr.add(Restrictions.and(

          Restrictions.or(  
          Restrictions.eq("companyName",companyName),
          Restrictions.isNotNull("companyName"))
    ,
    Restrictions.or(
            Restrictions.eq("state",state),
            Restrictions.isNotNull("state")),

       Restrictions.or(
               Restrictions.eq("employee.id",empId),
               Restrictions.isNotNull("employee.id")),

       Restrictions.or(
               Restrictions.eq("country",country),
               Restrictions.isNotNull("country"))
       ,
       Restrictions.or(
               Restrictions.eq("website",website),
               Restrictions.isNotNull("website"))
       ,
       Restrictions.or( 
               Restrictions.eq("primTech.id",pTech)
               ,Restrictions.isNotNull("primTech.id"))
     ,
     Restrictions.or(
             Restrictions.eq("secondTech.id",sTech),
             Restrictions.isNotNull("secondTech.id"))
      ,
      Restrictions.or(Restrictions.eq("statuss.id",status),
              Restrictions.isNotNull("statuss.id"))

        ));


return cr.list();

}

正如我上面提到的,这个列表在所有这些情况下都返回空值。 这里你是我的 POJO 类,

@Entity
@Table 
public class Companies implements Serializable {

@Id
@GeneratedValue
private int id;
private String companyName;
private String website;
private String contactName;
private String jobTitle;
private String address;
private String city;
private String pin;
private String country;
private String empSize;
private String state;
private String businessDomain;
private double rating;

@ManyToOne
@JoinColumn(name = "primTechID")
private PrimaryTech primTech;

@ManyToOne
@JoinColumn(name = "secondTechID")
private SecondaryTech secondTech;

@ManyToOne
@JoinColumn(name = "statusID")
private Status statuss;

private String phoneNo;
private String mobileNo;
private String email;
private Date datee;
private String description;
private String skyp;

@ManyToOne
@JoinColumn(name = "employee_id")
private Employee employee;

@OneToMany(mappedBy="companies",fetch=FetchType.LAZY)
@LazyCollection(LazyCollectionOption.FALSE)
private List<ContactedBy> contactedBy = new ArrayList<ContactedBy>();

这是我的控制器端,

@RequestMapping("admin/getdynamic")
public @ResponseBody 
String dataProcessing(@RequestParam int draw, 
                      @RequestParam int start,
                      @RequestParam int length,
                      @RequestParam(required=false) Integer tech,
                      @RequestParam(required=false)Integer sec,
                      @RequestParam(required=false)Integer emp,
                      @RequestParam String cont,
                      @RequestParam String state,
                      @RequestParam(required=false)Integer status,
                      @RequestParam String url,
                      @RequestParam String compName,
                      Model model){



    JsonNodeFactory factory = JsonNodeFactory.instance;
    ObjectNode objectNode = factory.objectNode();


List<Companies> list = companyService.getFilteredData(start,length,compName, state, emp, cont, url, tech, sec, status);
    ArrayNode node = factory.arrayNode();
    objectNode.set("data", node);

        list.forEach(lists -> {

            ArrayNode arr = factory.arrayNode();    
            arr.add(lists.getId());
            arr.add(lists.getCompanyName());
            arr.add(lists.getEmail());
            arr.add(lists.getContactName());
            arr.add(lists.getWebsite());
            arr.add(lists.getPrimTech().getName());
            arr.add(lists.getJobTitle());
            arr.add(lists.getPhoneNo());
            arr.add("<td><input type='checkbox' name='chkbox' id='chekbox' class='chekbox'/></td>");
            arr.add("<td width='40'><a class='creativeButton squareBlueButton editButton ct_edit_group' onClick='onUpdateClick("+lists.getId()+")'></a><a class='creativeButton squareRedButton closeButton'onClick='onDeleteClick("+lists.getId()+")'></a></td>");

            node.add(arr);
        });



     objectNode.put("draw", draw);
     objectNode.put("recordsTotal", companyService.getFilteredData(start,length,compName, state, emp, cont, url, tech, sec, status).size());
     objectNode.put("recordsFiltered", companyService.companyService.getFilteredData(start,length,compName, state, emp, cont, url, tech, sec, status).size());

    return objectNode.toString();
}

等待您的尽快答复.. 谢谢..

这里是hibernate触发的查询,注意最后的查询..

/* criteria query */ select this_.id as id1_0_7_, this_.Status_Count as Status_C2_0_7_, this_.address as address3_0_7_, this_.businessDomain as business4_0_7_, this_.city as city5_0_7_, this_.companyName as companyN6_0_7_, this_.contactName as contactN7_0_7_, this_.country as country8_0_7_, this_.datee as datee9_0_7_, this_.description as descrip10_0_7_, this_.email as email11_0_7_, this_.empSize as empSize12_0_7_, this_.employee_id as employe21_0_7_, this_.jobTitle as jobTitl13_0_7_, this_.mobileNo as mobileN14_0_7_, this_.phoneNo as phoneNo15_0_7_, this_.pin as pin16_0_7_, this_.primTechID as primTec22_0_7_, this_.rating as rating17_0_7_, this_.secondTechID as secondT23_0_7_, this_.skyp as skyp18_0_7_, this_.state as state19_0_7_, this_.statusID as statusI24_0_7_, this_.website as website20_0_7_, employee4_.id as id1_2_0_, employee4_.Report_to as Report_t7_2_0_, employee4_.email as email2_2_0_, employee4_.firstName as firstNam3_2_0_, employee4_.lastName as lastName4_2_0_, employee4_.password as password5_2_0_, employee4_.roleID as roleID8_2_0_, employee4_.username as username6_2_0_, employee7_.id as id1_2_1_, employee7_.Report_to as Report_t7_2_1_, employee7_.email as email2_2_1_, employee7_.firstName as firstNam3_2_1_, employee7_.lastName as lastName4_2_1_, employee7_.password as password5_2_1_, employee7_.roleID as roleID8_2_1_, employee7_.username as username6_2_1_, employeero8_.id as id1_3_2_, employeero8_.name as name2_3_2_, primtech1_.id as id1_4_3_, primtech1_.name as name2_4_3_, secondtech2_.id as id1_7_4_, secondtech2_.name as name2_7_4_, statuss3_.id as id1_8_5_, statuss3_.name as name2_8_5_, statuss3_.categoryId as category3_8_5_, statuscate12_.id as id1_9_6_, statuscate12_.categoryName as category2_9_6_ from Companies this_ inner join Employee employee4_ on this_.employee_id=employee4_.id left outer join Employee employee7_ on employee4_.Report_to=employee7_.id left outer join EmployeeRole employeero8_ on employee4_.roleID=employeero8_.id inner join PrimaryTech primtech1_ on this_.primTechID=primtech1_.id inner join SecondaryTech secondtech2_ on this_.secondTechID=secondtech2_.id inner join Status statuss3_ on this_.statusID=statuss3_.id left outer join StatusCategory statuscate12_ on statuss3_.categoryId=statuscate12_.id where ((this_.companyName is not null and this_.companyName=? and (this_.state is not null) and this_.state=? and (employee4_.id is not null) and employee4_.id=? and (this_.country is not null) and this_.country=? and (this_.website is not null) and this_.website=? and (primtech1_.id is not null) and primtech1_.id=? and (secondtech2_.id is not null) and secondtech2_.id=? and (statuss3_.id is not null) and statuss3_.id=?))

【问题讨论】:

  • 您在日志中看到生成的查询了吗?热衷于看到这一点
  • 你正在执行很多连接.. 这不是一件好事
  • 为什么很多join不好?
  • 它会增加查询运行的时间,还会导致大量重复行。许多数据库甚至不允许连接超过 5 个表
  • 您正在等待答案,但是...您的问题是什么?

标签: java hibernate hibernate-criteria


【解决方案1】:
      public List<Companies> getFilteredData(int start,
            int length,
            String companyName,
            String state,
            Integer empId,
            String country,
            String website,
            Integer pTech,
            Integer sTech,
            Integer status){



      List<Criterion> criterionList=new ArrayList<Criterion>();

      if(null!=companyName && !companyName.isEmpty())
          criterionList.add(Restrictions.like("companyName",companyName));
     if(null!=state && !state.isEmpty())
         criterionList.add(Restrictions.like("state",state));
     if(null!=empId )
         criterionList.add(Restrictions.eq("employee.id",empId));
     if(null!=country && !country.isEmpty())
         criterionList.add(Restrictions.like("country",country));
     if(null!=website && !website.isEmpty())
         criterionList.add(Restrictions.like("website",website));
     if(null!=pTech )
         criterionList.add(Restrictions.eq("primTech.id",pTech));
     if(null!=sTech )
         criterionList.add(Restrictions.eq("secondTech.id",sTech));
     if(null!=status )
         criterionList.add(Restrictions.or(Restrictions.eq("statuss.id",status));

         Criteria cr=factory.getCurrentSession().createCriteria(Companies.class);
         cr.createAlias("primTech","primTech");
         cr.createAlias("secondTech","secondTech");
         cr.createAlias("statuss","statuss");
         cr.createAlias("employee","employee");

         if(null!=criterionList && !criterionList.isEmpty())
             for(Criterion criterion:criterionList)
                 if(null!=criterion)
                     cr.add(criterion);


         return cr.list();

  }

这应该可以解决你的问题。

如果参数在标准列表中不为空,则上述方法为参数添加标准。最后,它将列表中存在的所有标准添加到标准查询中。这样,它只会对那些值已传递给此方法的参数添加限制。

希望对你有帮助

【讨论】:

  • 感谢 Zulfi,我确实在我的系统中运行了这段代码,但我仍然得到零列表。
  • @Pranav 将字符串的 eq 限制更改为类似限制.. 检查我上面的答案的编辑
  • @Pranav ..不客气..也请接受答案:)
猜你喜欢
  • 2012-01-14
  • 1970-01-01
  • 2013-01-03
  • 2011-02-27
  • 1970-01-01
  • 2019-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多