关于 JPQL 的问题,@NamedQuery
如果我有类似的东西,
@Entity
public class Facility {
...
@ManyToOne
@JoinColumn(name="CUSTOMER_FK")
private Customer customer;
...
}
我的 @NameQuery
会像这样
@NamedQuery(name="Facility.findByCustomerId", query="select c from Facility c where c.customer=:customer_fk")
或这样
@NamedQuery(name="Facility.findByCustomerId", query="select c from Facility c where c.CUSTOMER_FK=:customer_fk")
If I have something like this
@Entity
public class Facility {
...
@ManyToOne
@JoinColumn(name="CUSTOMER_FK")
private Customer customer;
...
}
does my @NameQuery
like this
@NamedQuery(name="Facility.findByCustomerId", query="select c from Facility c where c.customer=:customer_fk")
or like this
@NamedQuery(name="Facility.findByCustomerId", query="select c from Facility c where c.CUSTOMER_FK=:customer_fk")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 JPQL 时,您需要停止考虑外键并开始考虑对象。让我们仔细看看:
您的
Facility
是否有CUSTOMER_FK
财产?不,所以上面的查询是不正确的。下一篇:从语法上看,这个是正确的。但你仍然没有思考对象。在这里,查询希望您传递客户实例,而不是 FK。因此,我会像这样重写它(它是相同的查询,但它更好地传达了IMO的意图,而且我实际上会避免任何
foo_fk
约定,你不真正使用 JPA 操作 FK):如果您确实想通过 id 查找,您应该浏览关联并编写:
You need to stop thinking foreign keys and to start thinking object when using JPQL. Let's take a closer look:
Does your
Facility
have aCUSTOMER_FK
property? No, so the above query is incorrect. Next one:Syntacticly, this one is correct. But you're still not thinking object. Here, the query expect you to pass an instance of customer, not a FK. I'd thus rewrite it like this (it is the same query but it communicates IMO the intention much better and I'd actually avoid any
foo_fk
convention, you don't really manipulate FK with JPA):And if you really want to find by id, you should navigate through the association and write:
在 JPQL 中,您使用属性的名称,而不是数据库列。所以 - 第一个选择。
但是当您传递参数时,您传递的是整个对象,而不是它们的 ID。在您的情况下,您可以传递
Customer
实例,或者使 where 子句查找c.customer.id
(并且您最好将别名命名为f
,而不是c
)In JPQL you use the names of the properties, not the database columns. So - the first option.
But when you pass parameters, you pass the whole objects, not their IDs. In your case, you either pass a
Customer
instance, or make the where clause look forc.customer.id
(and you'd better name the aliasf
, notc
)