TABLE A ( id, type1, type2) id 是主键 TABLE B (idType1,idType2) 其中 (idType1,idType2) 是联合主键 eg: A id type1 type2 1 t1 null 2 null t2 3 t1 null 4 null t2 B : idType1 idType2 1 2 1 4 3 2 3 4 SELECT a.* FROM A a WHERE a.type1 = 't1' and a.id in ( SELECT b.idType2 FROM B b WHERE b.idType1 = 1 ) 请用 Hibernate 的 Criteria 来实现这句SQL 要直接拿到结果集。不要先搜出来 List<Long> idType2 作为条件再作第二次搜索
Criteria criteria = this.getSession().createCriteria(A.class); DetachedCriteria detachedCriteria = DetachedCriteria.forClass(B.class); detachedCriteria.setProjection(Projections.projectionList().add(Projections.groupProperty("b.idType2"))); detachedCriteria.add(Restrictions.eq("b.idType1", 1)); criteria.add(Subqueries.propertyIn("a.id", detachedCriteria)); criteria.add(Restrictions.eq("a.type1",“t1”)); if (criteria.list().size() > 0) { return (A) criteria.list().get(0); } else { return null; } Exzample: Criteria criteria = this.getSession().createCriteria(this.getPersistentClass()); DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ServiceProvider.class); ProjectionList proList4DetachedCriteria = Projections.projectionList(); proList4DetachedCriteria.add(Projections.groupProperty("id")); detachedCriteria.setProjection(proList4DetachedCriteria); ProjectionList proList4Criteria = Projections.projectionList(); proList4Criteria.add(Projections.countDistinct(International.PROP_CODE)); criteria.setProjection(proList4Criteria); // criteria.add(Restrictions.in(International.PROP_ID, new Object[] { 205, 584, 647, 648 })); criteria.add(Subqueries.propertyIn(International.PROP_ID, detachedCriteria)); Object counter = criteria.uniqueResult(); if (counter != null) { return ((Number) counter).intValue(); }