简体   繁体   English

通过休眠条件过滤记录

[英]Filter the records through hibernate criteria

I have used 8 different field filters into my application those are selected from eight different dropdowns ,now I am wishing to get the data accordingly the dropdown selected values.now if I have selected one value from the dropdown then it will fetch the data as per selected value,and rest of the fields are empty , if i select one another field then it will check the both field values,rest of the fields are empty and it will fetch the result from the database.to do so i have made a single query to fetch the data that is 我在应用程序中使用了8个不同的字段过滤器,这些过滤器是从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();

}

this list returns the empty values in all those cases as I mentioned above. 如上所述,在所有这些情况下,此列表都会返回空值。 here You are my POJO class, 这是我的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>();

here is my controller side, 这是我的控制方,

@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();
}

Awaiting for your answer as soon as possible.. Thanks.. 尽快等待您的答复..谢谢..

here the query fired by hibernate,notice the query from the end.. 这里是由休眠触发的查询,请注意从最后开始查询。

/* 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=?))
      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();

  }

This should solve you problem. 这应该可以解决您的问题。

The above method is adding criterion for an argument if its not null in a list of criterion . 如果参数列表中的参数不为null,则上述方法将为该参数添加条件。 At the end it is adding all the criterion present in the list to the Criteria query. 最后,它将列表中存在的所有条件添加到“条件”查询中。 In this way it will add restriction only for those arguments whose value has been passed to this method. 这样,它将仅对值已传递给此方法的那些参数添加限制。

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM