Entity to DTO conversion with JPA
I'm using DataNucleus as a JPA implementation to store my classes in my web application. I use a set of converters which all have toDTO()
and fromDTO()
.
My issue is, that I want to avoid the whole DB being sent over the wire:
- If I lazy load, the converter will try to access ALL the fields, and load then (resulting in very eager loading).
- If I don't lazy load, I'll get a huge part of the DB, since user contains groups, and groups contains users, and so on.
Is there 开发者_运维百科a way to explicitly load some fields and leave the others as NULL in my loaded class? I've tried the DataNucleus docs with no luck.
Your DTOs are probably too fine-grained. i.e. dont plan to have a DTO per JPA entity. If you have to use DTOs then make them more coarse grained and construct them manually.
Recently we have had the whole "to DTO or not to DTO, that is the question" discussion AGAIN. The requirement for them (especially in the context of a JPA app) is often no longer there, but one of the arguments FOR DTOs tends to be that the view has coarser data requirements.
To only load the data you really require, you would need to use a custom select clause containing only these elements that you are about to use for your DTOs. I know how painful this is, especially when it involves joins, which is why I created Blaze-Persistence Entity Views which will take care of making the query efficient.
You define your DTO as an interface with mappings to the entity, using the attribute name as default mapping, this looks very simple and a lot like a subset of an entity, though it doesn't have to. You can use any JPQL expression as mapping for your DTO attributes.
精彩评论