用hibernate构造where存在子查询

时间:2015-09-26 00:07:50

标签: hibernate dspace

我正在尝试使用hibernate创建以下查询。

select * from item 
where exists (
  select 1
  from metadatavalue mv
  where mv.dspace_object_id=item.uuid
  and text_value='No Date'
);

我在使用hibernate对象构建子查询时遇到了困难。

以下代码适用于我

Session session = (Session) context.getDBConnection().getSession();
Criteria criteria = session.createCriteria(Item.class, "item");
criteria.add(Restrictions.sqlRestriction("exists (select 1 from metadatavalue mv where mv.dspace_object_id=this_.uuid and text_value='No Date')"));

我想用hibernate对象创建这个查询。

Session session = (Session) context.getDBConnection().getSession();
Criteria criteria = session.createCriteria(Item.class, "item");
DetachedCriteria subcriteria = DetachedCriteria.forClass(MetadataValue.class);
subcriteria.add(???)
criteria.add(Subqueries.exists(subcriteria));

我不确定从子查询引用item.uuid(属性名“id”)的正确方法。

如果我尝试以下

Criteria criteria = session.createCriteria(Item.class, "item");
DetachedCriteria subcriteria = DetachedCriteria.forClass(MetadataValue.class,"mv");
subcriteria.add(Property.forName("mv.dspace_object_id").eqProperty("item.uuid"));
criteria.add(Subqueries.exists(subcriteria));
System.out.println("xx" + criteria.list().size());

我收到以下错误

java.lang.NullPointerException
    at org.hibernate.loader.criteria.CriteriaQueryTranslator.getProjectedTypes(CriteriaQueryTranslator.java:401)
    at org.hibernate.criterion.SubqueryExpression.createAndSetInnerQuery(SubqueryExpression.java:152)
    at org.hibernate.criterion.SubqueryExpression.toSqlString(SubqueryExpression.java:68)
    at org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:419)
    at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:123)
    at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:92)
    at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:95)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1604)
    at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)
    at org.dspace.core.Test.main(Test.java:37)

[

1 个答案:

答案 0 :(得分:0)

根据上面的建议,我使用了属性名而不是列名,我添加了投影。这解决了这个问题。

Criteria criteria = session.createCriteria(Item.class, "item");    
DetachedCriteria subcriteria = DetachedCriteria.forClass(MetadataValue.class,"mv");
subcriteria.add(Property.forName("mv.dSpaceObject").eqProperty("item.id"));
subcriteria.setProjection(Projections.property("mv.dSpaceObject"));
criteria.add(Subqueries.exists(subcriteria));
System.out.println("xx" + criteria.list().size());