Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 823
WhyNotHugo Avatar asked Feb 15 '10 15:02

WhyNotHugo


People also ask

How do I return DTO from JPA repository?

Interface-based DTO projections You first need to define an interface that defines a getter method for each attribute your projection shall contain. At runtime, Spring Data JPA then generates a class that implements that interface. you can then use that interface as the return type of a repository method.

Can we use entity class as DTO?

Short answer: Entities may be part of a business domain. Thus, they can implement behavior and be applied to different use cases within the domain. DTOs are used only to transfer data from one process or context to another.


1 Answers

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.

like image 61
Craig Day Avatar answered Sep 22 '22 16:09

Craig Day