How to write the Criteria queries dynamically?

佐手、 提交于 2019-12-13 04:42:09

问题


Hi I am writing a criteria query to fetch employees. I am using the Generic type as parameter for this method. The user can pass the class dynamically which class they want. For my employee class I want to add some restriction dynamically like if employee is true then I want to fetch that record, otherwise that record should not be fetch. But if the user gives only record without any restriction, than it has to fetch all records.

public static <T> List getRowCount(Class<T> classname) {

    Session ses = HibernateUtil.getSessionFactory().openSession();
    System.out.println("classname" + classname);
    List<SetPaginationRecords> s1 = new ArrayList<SetPaginationRecords>();
    try {
        Criteria crit1 = ses.createCriteria(classname);
        crit1.setProjection(Projections.rowCount());
        List l1 = crit1.list();
        Iterator it1 = l1.iterator();
        if (it1.hasNext()) {
            Object o = it1.next();
            totalNumberOfRecords = Integer.parseInt(o.toString());
        }
    }
}

This is my calling Method.

 List<SetPaginationRecords> paginationrecords = PaginationClass.getRowCount(EmployeeEntity.class);
        request.setAttribute("paginationrecords", paginationrecords);

回答1:


You may try something like this (which is just an example, outline how it could look like):

Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Employee.class);
if (userChoice.femalesOnly()) {
    criteria.add(Restrictions.eq("gender", Gender.FEMALE));
}
List<Employee> employees = criteria.list();

Here you create a criteria first, which has no restrictions. This means all records will be fetched. Then you check the user data, and dependent on the information given, augment the criteria. And last, call list() to fetch the result.




回答2:


You can use isAssignableFrom to determine what object you are dealing with.

public static <T> List getRowCount(Class<T> classname) {
   Criteria crit1 = ses.createCriteria(classname);

   if(Employee.class.isAssignableFrom(classname)){
      //Add some restriction to the criteria
   }
}


来源:https://stackoverflow.com/questions/22608634/how-to-write-the-criteria-queries-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!