QueryDSL SubQuery无法正常工作 - IllegalArgumentException:参数值与预期类型

时间:2017-09-11 22:00:58

标签: hibernate jpa querydsl

我试图在QueryDSL 4.1.4中使用子查询运行查询。版本3.x中的等效版本可以使用,但我似乎无法在版本4.1.4中使用它。不确定我是否遗漏了某些内容或是否有错误。任何意见都表示赞赏!

以下是相关代码:

PathBuilder productEntity = ...;
PathBuilder categoryEntity = ...;

JPQLQuery query = queryFactory.get().query();
query.distinct();

FilteredClause subQuery = JPAExpressions
    .select(productEntity.get("id", Long.class))
    .from(categoryEntity)
    .innerJoin(categoryEntity.get("products"), productEntity)
    .where(categoryEntity.get("id", Long.class).eq(categoryId));

query.where(productEntity.get("id", Long.class).notIn(subQuery));
query.fetch();

通过上述内容,我得到以下异常:

java.lang.IllegalArgumentException: Parameter value [select product.id
from Category category
  inner join treat(category.products as Product) as product
where category.id = ?1] did not match expected type [java.lang.Long (n/a)]
    at org.hibernate.jpa.spi.BaseQueryImpl.validateBinding(BaseQueryImpl.java:897)
    at org.hibernate.jpa.internal.QueryImpl.access$000(QueryImpl.java:61)
    at org.hibernate.jpa.internal.QueryImpl$ParameterRegistrationImpl.bindValue(QueryImpl.java:235)
    at org.hibernate.jpa.internal.QueryImpl$JpaPositionalParameterRegistrationImpl.bindValue(QueryImpl.java:371)
    at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:692)
    at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:181)
    at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:32)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:372)
    at com.sun.proxy.$Proxy365.setParameter(Unknown Source)
    at com.querydsl.jpa.impl.JPAUtil.setConstants(JPAUtil.java:56)
    at com.querydsl.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:102)
    at com.querydsl.jpa.impl.AbstractJPAQuery.fetchCount(AbstractJPAQuery.java:81)
...

似乎整个子查询被设置为参数,而Hibernate对此并不满意。我应该使用不同的QueryDSL语法来避免这个问题吗?

1 个答案:

答案 0 :(得分:0)

我发现问题是子查询属于FilteredClause类型。它没有造成任何编译错误,所以它可能会被Querydsl更好地处理,但在将子查询更改为以下内容后开始工作:

JPQLQuery subQuery = JPAExpressions
    .select(productEntity.get("id", Long.class))
    .from(categoryEntity)
    .innerJoin(categoryEntity.get("products"), productEntity);

// Keep the .where() call separate to retain the JPQLQuery object
subQuery.where(categoryEntity.get("id", Long.class).eq(categoryId));

// subQuery is now of type JPQLQuery instead of FilteredClause
query.where(productEntity.get("id", Long.class).notIn(subQuery));

List result = query.fetch();