The purpose of this blogpost is to explain main components and layers of a simple spring boot application and how to develop them.
Please find the source code for above application.
Rest Controller
- This is sample post method.
- Request body can be validated with @Validate annotation.
- HTTP status code for success scenario can be mentioned with @ResponseStatus annotation.
- URI is /sb/transactions.
- We can use ResponseStatusException for other HTTP status code based on each scenario.
Service Implementation
- Logging can be initialized by lombok @Slf4j annotation .
- Constructor with argument can be created with lombok @RequiredArgsConstructor annotation .
- We can map DTO to domain object and wise versa using transactionMapper .
- Using transactionRepository we can persist the domain object in database through JPA/JDBC .
JPA Repository/Backend Layer
- Most of the commonly used CRUD operations based on domain entity and primary key can be found from JpaRepository .
- For the native query, we have used a custom method.
- Native query can be found in the same domain entity class Transaction .
- The name of the native query should be : (Entity class name) . ( Domain Repository method name) - @NamedNativeQuery(name = "Transaction.findStatistics",
- @SqlResultSetMapping(name = "Mapping.StatisticsDto" : This will map sql result set to DTO.
- Please note that constructor of DTO have to create manually since order of argument data type should match with @SqlResultSetMapping columns.
public StatisticsDto(BigDecimal sum, BigDecimal avg, BigDecimal max, BigDecimal min,Long count)
Spring Boot Application : Where Every things Begins
Data Mapper
- We can use multiple mapper classes like DateMapper.class .
- componentModel = "spring" should be mentioned, then only mapstruct can be used within spring.
- DateMapper useful when we deserialize JSON to java object and wise versa since parser can identify Java 8 Date Time package.
Mockito with Spring Boot
- Don't forget to import correct @Test annotation.
import org.junit.jupiter.api.Test;
Spring Configuration
- Server port and name can be configured here
Application and Docker image building