关于 JPQL 的问题,@NamedQuery

发布于 2024-09-07 00:06:12 字数 502 浏览 5 评论 0原文

如果我有类似的东西,

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七七 2024-09-14 00:06:12

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

select c from Facility c where c.CUSTOMER_FK=:customer_fk

您的Facility 是否有CUSTOMER_FK 财产?不,所以上面的查询是不正确的。下一篇:

select c from Facility c where c.customer=:customer_fk

从语法上看,这个是正确的。但你仍然没有思考对象。在这里,查询希望您传递客户实例,而不是 FK。因此,我会像这样重写它(它相同的查询,但它更好地传达了IMO的意图,而且我实际上会避免任何foo_fk约定,你不真正使用 JPA 操作 FK):

select c from Facility c where c.customer = :customer

如果您确实想通过 id 查找,您应该浏览关联并编写:

select c from Facility c where c.customer.id = :id

You need to stop thinking foreign keys and to start thinking object when using JPQL. Let's take a closer look:

select c from Facility c where c.CUSTOMER_FK=:customer_fk

Does your Facility have a CUSTOMER_FK property? No, so the above query is incorrect. Next one:

select c from Facility c where c.customer=:customer_fk

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):

select c from Facility c where c.customer = :customer

And if you really want to find by id, you should navigate through the association and write:

select c from Facility c where c.customer.id = :id
江心雾 2024-09-14 00:06:12

在 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 for c.customer.id (and you'd better name the alias f, not c)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文