TABLE A ( id, type1, type2) id is the primary key
TABLE B (idType1,idType2) where (idType1,idType2) is the union primary key
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
)
Please use Hibernate's Criteria to implement this SQL
To get the result set directly. Do not search out List<Long> idType2 first as a condition and then do a second search
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;
}
Example:
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();
}