我正在使用Hibernate。我有以下SQL查询。我必须将其转换为标准。我怎样才能实现它?
SELECT DISTINCT username
FROM usertable
WHERE user_id in (SELECT DISTINCT user_id FROM someother_table);
答案 0 :(得分:2)
如果你将“user_id”映射为属性并且没有映射任何关系(如果你做了正确的属性可能是“myEntity.user.id”而不是“myEntity”,那么你应该做你正在寻找的东西。 USER_ID“)
Criteria criteria = getSession().createCriteria(MyEntity.class, "myEntity");
//setting projection to distinct(myEntity.username)
criteria.setProjection(Projections.distinct(Projections.property("myEntity.username")));
DetachedCriteria subCriteria = DetachedCriteria.forClass(MyOtherEntity.class, "myOtherEntity");
subCriteria.setProjection(Projections.distinct(Projections.property("myOtherEntity.user_id")));
criteria.add(Subqueries.propertyIn("myEntity.user_id", subCriteria));