4

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?

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
blank
  • 17,852
  • 20
  • 105
  • 159

3 Answers3

2

Does it matter in which entity class this is annotated?

From a technical point of view, it doesn't matter as you will use the name of a @NamedQuery to call it.

Why would you put it in one or the other?

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 the CustomerOrder entity because the query is about finding CustomerOrder, this is just where I'd expect to find it if I had to look for it.

Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
1

It doesn't matter. The general principle is to put it where it belongs logically. In your case - it'd better be in CustomerOrder

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
1

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

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Vasan
  • 11
  • 2