Search code examples
javajpajakarta-eenamed-query

How do you decide in which entity classes to put JPA NamedQuery annotations?


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?


Solution

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