Let’s get it all working together.

REST has quickly become the de-facto standard for building web services on the web because they’re easy to build and easy to consume. In the second part of this series about Spring Boot with JDBCTemplate, we’ll explore how to create a Rest application.

We talked about the database integration in the first part, and we showed a test with H2. The next step is to expose this model as a rest resource, and every time a team needs to do it, the first question is about the DTO.

Data Transfer Objects, known affectionately as DTOs, are the subject of many discussions about developing Java applications, especially rest and MVC applications.

As with any architecture, a team needs to handle the trade-off of having it or don’t it.

  • Increases the complexity.
  • There is the possibility of duplicate code.
  • Adding a new layer impacts the delay layer, that is, the possible loss of performance.

The other option is to add the DTO layer, which basically guarantees the decoupling of the view and the model, as mentioned previously.

  • It makes it explicit which fields will go to the view layer. Yes, there are several annotations in various frameworks that indicate which fields will not be displayed. However, if you forget to write it down, you can export a critical field accidentally, for example, the user’s password.
  • Facilitates drawing in object orientation. One of the points clean code clarifies object orientation is that OOP hides the data to expose the behaviour, and the encapsulation helps with that.
  • Facilitates updating the database. It is often essential to refactor, migrate the database without this change impacting the customer. This separation facilitates optimisations, modifications to the database without affecting the visualisation.
  • Versioning, backward compatibility is an important point, especially when you have an API for public use and multiple customers, so it is possible to have a DTO for each version and evolve the business model without worry.
  • Another benefit is found in the ease of working with the rich model and creating an API that is bullet-approved. For example, within my model, I can use a money API; however, I export as a simple object with only the monetary value for visualisation within my visualisation layer. That is the right old String in Java.
  • CQRS. Yes, is Command Query Responsibility Segregation about separating responsibility for writing and reading data, and how to do this without DTOs?

#java #tutorial #spring #spring boot #rest #jdbctemplate #dto

Introduction to Spring Boot and JDBCTemplate: Introduction to REST
1.20 GEEK