Recently Ive seen so many devs working with the stack Spring/JPA and returning all these JPA entities on their rest controllers.

In my opinion it's a BAD PRACTICE for several reason such: Transactions (should never start on the REST controllers), sensible informations can be exposed by mistake, maintenance of the entities is hard since it's easy to break the rest interface, also many others.

If you have the view representation like DTO's, makes your life easier.

I would like to understand why, or if really are advantages of using this approach.

  • 1
    BTW, what does returning JPA entities have to do with invoking a transaction in a controller? – Andy Jul 12 '18 at 14:16

For quite simple apps, returning such entities works just fine and gets you started really quick. You are likely to need those for the database interactions anyway and the returned entities are usually 1:1 mapping to database.

For more robust applications which you want to scale better, completely circumventing those entities on reads by using plain SQL queries and DTOs is generally the more favourable approach.

For the write side, it's sometimes also better to use some form of a command pattern in your application (controller) layer, such as RegisterUser DTO, and only convert the command to actual JPA entity in your service layer.

| improve this answer | |

I have worked in large web applications using the JavaEE stack and this was perfectly acceptable. You could use these entities in the JSP layer, the Beans layer, even for other stuff such as validations etc. This made your life easier and kept the code simple and clean. The overall solution still adhered to the JavaEE architecture.

However, when you are using a similar approach but outside of JavaEE, it can throw up problems that you otherwise would not encounter. The behavior of these entity classes outside JavaEE container, example in Spring or any other framework for example would be undefined. I always found using plain POJO or DTOs or JSONs much more beneficial in these cases.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.