简体   繁体   中英

how to write with clause using criteria in hibernate

I have a query where i used WITH clause to generate results.

 WITH employee AS (SELECT * FROM Employees)
 SELECT * FROM employee WHERE ID < 20
 UNION ALL
 SELECT * FROM employee WHERE Sex = 'M'

Could you please any one let me know how to write this query in hibernate using criteria specially when with clause present in query.

First, you've dramatically over-complicated your SQL. Here's how your query should look in pure SQL:

SELECT * FROM Employees WHERE ID < 20 or Sex = 'M'

Next, assuming you have a Hibernate entity (let's call it Employee.java for now), your HQL equivalent would be:

from Employee e where e.id < 20 or e.sex = 'M'

To do it with a Criteria , you'd do the following:

final Criteria criteria = getSession().createCriteria(Employee.class);
criteria.add(Restrictions.or(
        Restrictions.lt("id", 20),
        Restrictions.eq("sex", "M")
    )
);
criteria.list();

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