简体   繁体   中英

How to write the Criteria queries dynamically?

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);

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.

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
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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