如何动态编写条件查询? [英] How to write the Criteria queries dynamically?

查看:135
本文介绍了如何动态编写条件查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在编写一个标准查询来获取员工.我使用通用类型作为此方法的参数.用户可以动态地将所需的类传递给该类.对于我的员工类,我想动态添加一些限制,例如,如果employee是true,那么我想获取该记录,否则不应获取该记录.但是,如果用户仅给出记录而没有任何限制,则它必须获取所有记录.

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

这是我的呼叫方法.

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

在这里您首先创建一个没有限制的条件.这意味着将提取所有记录.然后,您检查用户数据,并根据给定的信息扩充标准.最后,调用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.

这篇关于如何动态编写条件查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆