Java Magazine, May/June 2018
ORACLE COM JAVAMAGAZINE MAY JUNE 2018 37 design patterns Use cases that require a few attributes of multiple associated entities are also common reasons to use DTOs You can of course load the entities with all their associations but that is not as eficient as selecting only the attributes that you need for your use case Disadvantages of DTOs The DTO design pattern also has a few disadvantages DTOs introduce a lot of redundancy when they are identical to your entities That creates additional efort whenever you need to change or remove one of these attributes And as you probably know from your own experience its dificult to decouple the API of CRUD use cases from the persistence layer Even so DTOs enable you to change your entities without changing your API Real world projects show that if you change your entities you most often also need to change your DTOs If you find yourself in a situation in which your DTO is identical to your entity and youre always changing both of them you should consider removing the DTO and using the entity instead Conclusion Most Spring and Jakarta EE applications use JPA to implement their persistence layer Its no surprise that you can choose from several well established design patterns that help you to implement a robust and eficient persistence layer In this article I discussed why you should prefer composition over inheritance looked at the repository and DTO patterns and compared two options for initializing lazily fetched associations in the business layer to avoid the Open Session in View antipattern These are just a few of the most commonly used patterns If you want to learn more about design patterns for JPA and Hibernate you should also take a look at transactional patterns such as the Session per Request pattern or the Conversation pattern article Thorben Janssen @ thjanssen123 is an independent consultant a trainer and the author of Hibernate Tips More than 70 solutions to common Hibernate problems He has been working with Java and Java EE for more than 15 years and is a member of the CDI 20 expert group JSR 365 He writes about JPA Hibernate and other persistence related topics on his blog Thoughts on Java
You must have JavaScript enabled to view digital editions.