我想要一个针对以下SQL查询的hibernate查询

时间:2016-06-28 06:44:24

标签: mysql hibernate

我想在hibernate查询

我获得了多个员工ID 单个leaveId

我为以下内容设计了有效的MySql查询:

select * from lms_employee_leave_records 
         where (employee_id=2633 or  
                employee_id=2634 or employee_id=2635) 
                and leave_category_id=1;

我做了一个示例查询: 我应该做什么查询,因为可能有N不。查询中的员工但是离开ID只有一个。所以我设计的是:

criteria.add(Restrictions.and(Restrictions.or(c1,c2), c3));

但问题是在OR中,我无法为:

设置多个员工ID
Restrictions.eq("employee.employeeId", employee.getEmployeeId())

2 个答案:

答案 0 :(得分:0)

首先,您需要为您的表lms_employee_leave_records创建实体映射作为EmployeeRecords

更多关于这里的映射 https://docs.jboss.org/hibernate/stable/annotations/reference/en/html/entity.html

(我假设在您创建实体时,您将使用的成员名称与表中的列名称相同)

使用hibernate本机API,您将有两个选项

<强> HQL

以下是您可以使用的HQL查询

from EmployeeRecords as e
     where e.employee_id in (2633,2634,2635)
            and e.leave_category_id=1;

在会话

上使用createQuery()执行上述查询

有关HQL的更多信息

https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/queryhql.html

<强>标准

以下是您在条件中查询

session.createCriteria(EmployeeRecords.class)
.add(Restrictions.in("employee_id",list)) //list will have list of emp ids
.add(Restrictions.eq("leave_category_id",1))
.list()

有关此处标准的更多信息

https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/querycriteria.html

修改

而不是这个

criteria.add(Restrictions.and(Restrictions.or(c1,c2), c3));

你可以这样做

    Criterion c1=Restrictions.eq("employee_Id", empId1);
    Criterion c2=Restrictions.eq("employee_Id", empId2);
    Criterion c3=Restrictions.eq("employee_Id", empId1);

    Criterion or=Restrictions.or(c1,c2,c3);

    session.createCriteria(EmployeeRecords.class)
    .add(or)
    .add(Restrictions.eq("leave_category_id",1))
    .list()

empId1,empId2,empId3将是你持有emp ID的变量

答案 1 :(得分:0)

List al = new ArrayList();
                        al  .add(2633);
                        al.add(2634);
                        al.add(2635);
                        Criteria ct = getSession().createCriteria(EmployeeLeaveRecords.class)
                                .add(Restrictions.eq("leave_category_id",1))
                                .add(Restrictions.in("employee_id", al));