I want to write a JPA application, but I have problems understanding the repository and service concepts:
Consider we have 3 entities: A, B and C.
Entity A needs to have B and C set: A.setB(B), A.setC(C) before it is saved.
Also for read, I want to return only DTOs since they will free me from LazyInitializationException, Open Session In View Anti-Pattern, etc, and for modifying data I will use entities ( these guidelines are also described in this book High-Performance Java Persistence).
First of all, the user will make a HTTP POST with some data which will be converted into ABCGuiObject. The REST controller will call serviceA.save(ABCGuiObject).
Persist options:
Option #1 - The service will create 3 objects A, B ,C and pass them to repositoryA.save(A,B,C). The repositoryA will do inside a.setB and a.setC.
Option #2 - The service will create 3 objects A, B ,C, do a.setB and a.setC and call repositoryA.save(A).
DTO retrieval
I would like to write a JPQL query to get some DTO. I do not want to convert entities to DTO, but retrieve them directly with JPQL.
Option #1 - repositoryA will return directly a DTO.
Option #2 - the service will pass a JPQL query to the repositoryA, which will have a general query method which returns a DTO.
What approaches do you recommend?
Write data
The Service layer should construct the graph of entities
A
,B
andC
and connect them accordingly (a.setB
anda.setC
) and passA
,B
andC
to the Repository. If you have one-to-many associations, you can cascade entity state transitions.Read data
If you want to return DTOs, you are better off fetching DTOs directly from JPA and Hibernate. So, you have two options:
ResultTransformer