OpenJPA如何使用join fetch在集合上使用WHERE条件?

时间:2012-07-19 05:57:11

标签: join jpql openjpa

我在WebSphere Application Server 8上使用OpenJPA 2.1。 我有这样的双向oneToMay关系:

@Entity(name = "table1")
public class Table1  {
    @Id
    @Column(columnDefinition = "DATE")
    private Date date;
    @OneToMany(mappedBy = "date", targetEntity = Table2.class, fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    private List<Table2> table2List;
}

@Entity(name = "table2")
public class Tabl2{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "fk_date", nullable = false)
    private Table1 table1;

    @Column(name = "value", nullable = false, columnDefinition = "INT")
    private int value;

}

现在我想在table2上选择整个table1实体,条件如下:

TypedQuery<WeekBean> q = em.createQuery(
    "SELECT t1 from table1 t1 JOIN FETCH t1.table2List t2 WHERE t2.value = :value",
    t1.class);

但这不起作用,因为我得到了一个ArgumentException:

Exception in thread "main" <openjpa-2.1.1-SNAPSHOT-r422266:1141200 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: " Encountered "f" at character 50, but expected [",", ".", "GROUP", "HAVING", "INNER", "JOIN", "LEFT", "ORDER", "WHERE", <EOF>]." 
    at org.apache.openjpa.kernel.jpql.JPQLParser.parse(JPQLParser.java:51)
    at org.apache.openjpa.kernel.ExpressionStoreQuery.newCompilation(ExpressionStoreQuery.java:154)
    at org.apache.openjpa.datacache.QueryCacheStoreQuery.newCompilation(QueryCacheStoreQuery.java:262)
    at org.apache.openjpa.kernel.QueryImpl.newCompilation(QueryImpl.java:672)
    at org.apache.openjpa.kernel.QueryImpl.compilationFromCache(QueryImpl.java:654)
    at org.apache.openjpa.kernel.QueryImpl.compileForCompilation(QueryImpl.java:620)
    at org.apache.openjpa.kernel.QueryImpl.compileForExecutor(QueryImpl.java:682)
    at org.apache.openjpa.kernel.QueryImpl.compile(QueryImpl.java:589)
    at org.apache.openjpa.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:996)
    at com.ibm.ws.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:107)
    at com.ibm.ws.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:86)
    at com.ibm.ws.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:34)
    at org.apache.openjpa.persistence.EntityManagerImpl.createQuery(EntityManagerImpl.java:974)

如何在集合中使用带有条件的JOIN FETCH?

最诚挚的问候Veote

1 个答案:

答案 0 :(得分:2)

根据JPA 2.0规范,不支持此类构造,看起来OpenJPA也不提供供应商扩展的功能:

  

FETCH JOIN子句右侧引用的关联   必须是属于作为a返回的实体的关联   查询结果。不允许指定标识   FETCH右侧引用的实体的变量   JOIN子句,因此引用隐式获取的实体   不能出现在查询的其他地方。

在您的情况下,这意味着您无法定义t2,因此您无法在WHERE子句中使用它。