如何决定在哪些实体类中放置 JPA NamedQuery 注释?
假设我有一个 Customer - CustomerOrder 一对多双向关系,其中 CustomerOrder 保存每个订单的总价值。
如果我有一个查询来查找特定客户的所有订单的总价值:
select SUM(o.orderValue) from CustomerOrder o where o.customer = :customer
在哪个实体类中进行注释是否重要?为什么要把它放在其中之一?
Say I have a Customer - CustomerOrder one-to-many bi-directional relationship with the CustomerOrder holding the total value of each order.
If I had a query to find the total value of all orders for a particular customer :
select SUM(o.orderValue) from CustomerOrder o where o.customer = :customer
Does it matter in which entity class this is annotated? Why would you put it in one or the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从技术角度来看,这并不重要,因为您将使用
@NamedQuery
的name
来调用它。但是,从“逻辑”的角度来看,将 @NamedQuery 放在“自然”所属的位置肯定会简化维护。在您的示例中,我会将查询放入
CustomerOrder
实体中,因为查询是关于查找CustomerOrder
的,这正是我所期望的如果我必须寻找的话,找到它。From a technical point of view, it doesn't matter as you will use the
name
of a@NamedQuery
to call it.But, from a "logical" point of view, putting the
@NamedQuery
where is "naturally" belongs will definitely ease the maintenance. In your example, I would put the query in theCustomerOrder
entity because the query is about findingCustomerOrder
, this is just where I'd expect to find it if I had to look for it.没关系。
总的原则是把它放在符合逻辑的地方。在你的情况下 - 最好在
CustomerOrder
It doesn't matter.
The general principle is to put it where it belongs logically. In your case - it'd better be in
CustomerOrder
将它们放入应在 persistence.xml 中声明的 XML 映射文件中。请参阅这个很棒的链接: arjan -tijms.omnifaces.org/2010/09/where-to-put-named-queries-in-jpa
许多查询并不“自然”属于实体(而且您还必须修改实体代码,如果你把它们放在那里,每次你需要一个新的查询)。
Put them in the XML mapping files which should be declared in the persistence.xml. See this great link: arjan-tijms.omnifaces.org/2010/09/where-to-put-named-queries-in-jpa
Lots of queries do not 'naturally' belong with the entity (and further you have to modify the entity code, if you put them there, each time you need a new query).