我有两个模型,LocationLocationAttribute,具有多对多关系。
我有一个LocationAttribute ID列表,并希望找到至少有一个的所有Locations
这些属性。

Location.java:

@Entity
public class Location {

    @Id
    @GeneratedValue
    @Column(name="LOCATION_ID")
    protected int id;

    @ManyToMany(targetEntity = LocationAttribute.class)
    @JoinTable(name="LOCATION_TO_LOCATION_ATTRIBUTE",
            joinColumns = @JoinColumn(name="LOCATION_ID", referencedColumnName = "LOCATION_ID"),
            inverseJoinColumns = @JoinColumn(name="LOCATION_ATTRIBUTE_ID", referencedColumnName = "LOCATION_ATTRIBUTE_ID")
    )
    private List<LocationAttribute> locationAttributes;
}

LocationAttribute.java:
@Entity
public class LocationAttribute {

    @Id
    @GeneratedValue
    @Column(name="LOCATION_ATTRIBUTE_ID")
    protected int id;
}

我尝试了以下QueryDSL代码:
List<Integer> locationAttributeIds = new ArrayList<Integer>();
locationAttributeIds.add(1);
locationAttributeIds.add(2);
locationAttributeIds.add(3);

QLocation location = QLocation.location;
JPAQuery query = new JPAQuery(entityManager, JPQLTemplates.DEFAULT);
query.from(location) .where(location.locationAttributes.any().id.in(locationAttributeIds));
query.list(location);

如果locationAttributeIds具有0或1个元素,则代码工作正常。但是,当我有多个元素时,会出现此错误:
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: , near line 5, column 53 [select location
from ch.locatee.test.querydslerror.locatee.Location location
where exists (select location_locationAttributes_cc6d8
from location.locationAttributes as location_locationAttributes_cc6d8
where location_locationAttributes_cc6d8.id in :x1_0_, :x1_1_, :x1_2_)]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1750)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:458)
    at com.mysema.query.jpa.impl.AbstractJPAQuery.getResultList(AbstractJPAQuery.java:194)
    at com.mysema.query.jpa.impl.AbstractJPAQuery.list(AbstractJPAQuery.java:246)
    at ch.locatee.test.querydslerror.locatee.AppTest.testSomething(AppTest.java:63)

我找到了很多与该问题相关的站点,但不确定如何解决该问题。
  • https://github.com/querydsl/querydsl/issues/72
  • How to set collection items for in-clause in jpql?
  • https://hibernate.atlassian.net/browse/HHH-6913
  • https://github.com/querydsl/querydsl/issues/271

  • 我做了一个快速测试项目,您可以在Github上找到它:https://github.com/bekoeppel/QueryDslInErrorTestmvn test产生以上错误。

    我希望您能从列表中找到至少具有Locations之一的所有LocationAttribute.id的想法。谢谢!

    最佳答案

    请改用以下JPAQuery构造函数

    new JPAQuery(entityManager);
    
    JPQLTemplates提供通用序列化,无法找到Hibernate的所有JPQL变体。仅使用EntityManager参数,Querydsl将为您选择正确的JPQLTemplates子类实例。

    关于java - QueryDSL意外 token ,带有any()和in子句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29865648/

    10-12 02:32