Question in short: How can you map/calculate a derived field using JDO/DataNucleus?
Example
An Order
can have one or more Items
. The field totalItemAmount
is the sum of all Items
and their amounts
. totalItemAmount
should not exist as a field in the datastore, but should be calculated.
With Hibernate one could use @Formula
to annotate totalItemAmount
- see https://stackoverflow.com/a/2986354/2294031 .
Is there an equivalent for JDO/DataNucleus?
Workarounds
Because I have not found anything yet, I considered using alternative approaches. But I am not sure which one would be appropriate.
- Implementing
totalItemAmount
as a method: The total amount of items could be calculated with a method (eg.Order.getTotalItemAmount()
). The method iterates over allItems
of theOrder
and sums up theamount
of eachItem
. But I imagine this approach would be very slow if I want to display an overview of many orders. Because each timegetTotalItemAmount()
gets called, allItems
of theOrder
will be (unnecessarily) fetched. - Defining a custom query: Is it possible to define a custom query, which will be used, when DataNucleus obtains
Orders
from the datastore? - Treating
totalItemAmount
as a "normal" column (likenumber
):totalItemAmount
will be an integer column and everytime the list ofItems
from theOrder
gets updated, thetotalItemAmount
will be updated also. But I do not like this approach, because it could lead to inconsistency - If the order gets modified outside the context (eg. using plain SQL), the content oftotalItemAmount
could be wrong. - Using a SQL view: I could define a view as described in Hibernate Derived Properties - Performance and Portability. But this would introduce a considerable amount of work and future maintenance - imho too much for the gain.
Is there another way to solve this problem?
Off-Topic: Feel free to comment on my writing, as I really would like to improve it.