Suppose the cenário where customers puts orders on our system. So, for simplicity, we have 2 entities :
Customer
- CustomerID
- Name
Order
- Customer
- OrderID
- OrderValue
We have a REST Service that is used to save/update a Customer and also, a REST Service that is used to POST orders.
In JPA, actually, the Order
entity has a ManyToOne
relationship to Customer
entity. So, assuming that I'm not using DTO
, I need to call my OrderService
passing, at least, something like this JSON
:
{
"customer": {
"customer_id": 10
},
"order_id": 40,
"order_value": 200.1
}
And, when I return the order to the RestClient, all Customer
is being returned, since it's being loaded during the process.
So, thinking on complex systems where the are a lot of Entities that are 'nested', is it acceptable to (or at least not a bad practice) to create entities that references only the key instead of the object itself? Something like:
Order
- CustomerID
- OrderID
- OrderValue
I'm new to JPA/Hibernate and I come from a world where all entities were loaded manually from the Database. So, when dealing with an Order, we used to load only the Customer.CustomerId
instead of all Customer data. Here, in this example, I think that I have two options: Load all Customer (using FetchType.EAGER or load nothing (using FetchType.LAZY), so, there is no way (at least that I know) to return to the RESTClient an Order object that contais only it's CustomerID (at least, without manually setting order.customer.customer_id manually, thing that sounds a little bit hacky).
Thanks a lot!