使用@ManyToOne对象进行JPA查询

时间:2018-03-30 13:47:05

标签: java jpa jpql

我有这些JPA对象:

public class BB {

    // ...

    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "date")
    protected Date date;

    // ...

}

public class B extends BB {

    // ...

    /**
     * The referred a.
     */
    @ManyToOne(optional = false)
    private AA a;

    // ...

}

public class A extends AA {

    // ...

    private String ID;

}

现在我想使用JPA执行以下查询:

SELECT * FROM A as a INNER JOIN B as b ON a.ID = b.A_ID ORDER BY b.date

我试过了:

StringBuilder builder = new StringBuilder("SELECT a FROM ").
    append(A.class.getSimpleName()).
    append(" a JOIN ").
    append(B.class.getSimpleName()).
    append(" b").
    append(" WHERE 1=1 ORDER BY b.date");

Query query = entityManager.createQuery(builder.toString());

query.getResultList();

但它不起作用,它给了我一个

"Encountered \"\" at character 36, but expected: [].\" while parsing JPQL \"SELECT a FROM A a JOIN B b WHERE 1=1\". See nested stack trace for original parse error."

错误。

你可以帮帮我吗? 我不是JPA的专家。

由于

1 个答案:

答案 0 :(得分:0)

您需要加入某个字段,而不是实体:尝试     JOIN a.B b

如果存在,或者在必要时以相反的方式写入