使用条件的Hibernate嵌套查询

时间:2013-06-26 12:40:06

标签: java spring hibernate postgresql jpa

是否可以在sql下创建生成条件:

select name from (select distinct name from person) as aliasname  order by lower(name);

这里有两个sql -

  1. select distinct name from person

  2. select name from <output of 1> as aliasname order by lower(name)

  3. 我想创建条件,然后执行criteria.list()

2 个答案:

答案 0 :(得分:1)

我认为,这将满足您的需求:

criteria.addOrder(Order.asc("name").ignoreCase())
        .setProjection(Projections.distinct(Projections.property("name")))
        .list();

或者,此标准使用名为projection的DetachedCriteria作为子查询:

DetachedCriteria distinctNamesCriteria = DetachedCriteria.forClass(Person.class);
distinctNamesCriteria.setProjection(Projections.distinct(Projections.property("name")));

criteria.add(SubQueries.propertyIn("name", distinctNamesCriteria))
        .addOrder(Order.asc("name").ignoreCase())
        .list();

答案 1 :(得分:-1)

我没有给你答案,但为什么你要做第二次选择?

SELECT DISTINCT NAME FROM PERSON AS ALIASNAME ORDER BY LOWER(NAME)

将返回相同的数据。