关于JPQL,@ NamedQuery的问题

Tha*_*ham 2 java jpa jpql java-ee

如果我有这样的事情

@Entity
public class Facility {
    ...
    @ManyToOne
    @JoinColumn(name="CUSTOMER_FK")
    private Customer customer;
    ...
}
Run Code Online (Sandbox Code Playgroud)

@NameQuery喜欢这样吗

@NamedQuery(name="Facility.findByCustomerId", query="select c from Facility c where c.customer=:customer_fk")
Run Code Online (Sandbox Code Playgroud)

或者像这样

@NamedQuery(name="Facility.findByCustomerId", query="select c from Facility c where c.CUSTOMER_FK=:customer_fk")
Run Code Online (Sandbox Code Playgroud)

Pas*_*ent 5

在使用JPQL时,您需要停止考虑外键并开始思考对象.让我们仔细看看:

select c from Facility c where c.CUSTOMER_FK=:customer_fk
Run Code Online (Sandbox Code Playgroud)

FacilityCUSTOMER_FK房产吗?不,所以上面的查询不正确.下一个:

select c from Facility c where c.customer=:customer_fk
Run Code Online (Sandbox Code Playgroud)

从句法上讲,这个是正确的.但你仍然没有想到对象.在这里,查询期望您传递客户实例,而不是FK.我这样重写它(它相同的查询,但它更好地传达IMO的意图,我实际上避免任何foo_fk约定,你没有真正用JPA操纵FK):

select c from Facility c where c.customer = :customer
Run Code Online (Sandbox Code Playgroud)

如果你真的想通过id找到,你应该浏览关联并写:

select c from Facility c where c.customer.id = :id
Run Code Online (Sandbox Code Playgroud)