hibernate条件API中的子查询

时间:2016-04-14 12:27:40

标签: java hibernate hibernate-criteria

我试图在hibernate Criteria中生成这个查询:

 select count(*) from res_mapping where mop_id = ? and role_name = ? and 
mop_id not in(select mop_id from res_mapping_mod where mop_id = ? and role_name = ?);

这是我的方法:

public static boolean roleHasMenu(String roleName, String mopId) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        long count = 0;
        try {
            tx = session.beginTransaction();
            DetachedCriteria subquery = DetachedCriteria.forClass(ResMappingMod.class);
            subquery.add(Restrictions.eq("roleName", roleName));
            subquery.add(Restrictions.eq("mopId", mopId));
            subquery.setProjection(Projections.property("mopId"));
            Criteria cr = session.createCriteria(ResMapping.class);
            cr.add(Restrictions.eq("roleName", roleName));
            cr.add(Restrictions.eq("mopId", mopId));
            cr.add(Subqueries.notIn("mopId", subquery));
            count = (Long) cr.setProjection(Projections.rowCount()).uniqueResult();
            tx.commit();
        } catch (Exception asd) {
            log.debug(asd.getMessage());
            if (tx != null) {
                tx.rollback();
            }
        } finally {
            session.close();
        }
        return count > 0;
    }

我得到的是:

    select count(*) as y0_ from GLS.RES_MAPPING this_ where this_.ROLE_NAME=? 
and this_.MOP_ID=? and ? not in (select this_.MOP_ID as y0_ from 
GLS.RES_MAPPING_MOD this_ where this_.ROLE_NAME=? and this_.MOP_ID=?)

not in之前我有一个参数而不是一个字段。可能是什么问题?

1 个答案:

答案 0 :(得分:1)

尝试这个

cr.add(Subqueries.propertyNotIn(" id",subCriteria));

谢谢, 阿米特库马尔

相关问题