e. Repository
Now, with the controller implemented, we can move on to the service layer of the Account microservice. The service layer is responsible for the business logic of the microservice, and it interacts with the repository layer to handle the data persistence of the Account entity. The service layer is implemented in the AccountService class, which contains the methods for creating, finding (all, or one by id), and deleting accounts. The AccountService class uses the AccountRepository to handle the data persistence of the Account entity, and the AccountParser to handle the parsing of the input and output of the API endpoints.
From previous hands-on, we have already see that this microservice uses clean architecture, which means that the service layer is independent of the controller layer and the repository layer. This allows us to easily test the business logic of the service layer without having to worry about the details of the controller layer or the repository layer. The following diagram illustrates the architecture of the Account microservice, showing the relationships between the different layers and classes:
sequenceDiagram
title Clean architecture's approach
Actor Request
participant Controller as Controller<br>Resource
participant Service@{ "type": "control" }
participant Repository@{ "type" : "entity" }
participant Database@{ "type" : "database" }
Request ->>+ Controller: Rest API (JSON)
Controller ->>+ Service: parser (AccountIn -> Account)
Service ->>+ Repository: parser (Account -> AccountModel)
Repository ->>+ Database:
Database ->>- Repository:
Repository ->>- Service: parser (Account <- AccountModel)
Service ->>- Controller: parser (AccountOut <- Account)
Controller ->>- Request: Rest API (JSON) The relationships between the different layers is done though the use of different DTOs (Data Transfer Objects). Then, to translate between the different layers, we use parsers, which are responsible for converting the DTOs to the entities and vice versa.
-
The
AccountParserclass is responsible for this translation, and it contains the methods for converting theAccountInDTO to theAccountentity, and theAccountentity to theAccountOutDTO. -
Also
AccountModelis the class that represents the database model of the Account entity, which is used by theAccountRepositoryto handle the data persistence of the Account entity. TheAccountModelclass contains the attributes of the Account entity and it is annotated with JPA annotations to define the mapping between the class and the database table.
1. The Object-Relational Mapping (ORM)
This project uses a Relational Database (PostgreSQL) to store the data of the Account entity. But, the Java programming language is an object-oriented programming language, which means that we need a way to map the relational data to the object-oriented data
Object-Relational Mapping (ORM) is a programming technique that allows developers to interact with a relational database using an object-oriented programming language. It provides a way to map database tables to classes and database records to objects, allowing developers to work with data in a more intuitive and natural way. In the context of the Account microservice, we will use an ORM framework, JPA, to handle the data persistence for the Account entity, which will allow us to easily create, read, update, and delete accounts in the database.
Here, we can see the code that solves the data persistence concerns of the Account microservice, including the AccountModel class, which represents the database model of the Account entity, and the AccountRepository interface, which is responsible for the data persistence of the Account entity using JPA.
2. Database Migrations
Once we have the ORM set up, we need to manage our database schema changes. As our application evolves, we may need to add new tables, modify existing tables, or change the data types of columns. To manage these changes, we will use a database migration tool called Flyway1.
Flyway is a database migration tool that allows us to manage and version our database schema changes. It provides a way to define and execute database migrations, which are scripts that modify the database schema, such as creating tables, adding columns, or changing data types. In the context of the Account microservice, we will use Flyway to manage our database migrations, ensuring that our database schema is always up-to-date and consistent across different environments.
In the code, we have a db/migration directory, which contains the migration scripts for the Account microservice. Each migration script is named in a specific format, starting with a version number (e.g., V2026.08.24.001) followed by a description of the migration (e.g., create_schema). These migration scripts will be executed in order by Flyway to ensure that our database schema is always up-to-date.
At every start, Flyway compares the scripts with what the database has already run and applies only the new ones, before JPA starts:
sequenceDiagram
participant A as account (starting)
participant F as Flyway
participant D as db (PostgreSQL)
A->>F: migrate
F->>D: read accounts.flyway_schema_history
D-->>F: versions already applied
F->>D: V2026.08.24.001 create_schema
F->>D: V2026.08.24.002 create_table
F->>D: record both versions
F-->>A: schema up to date
A->>A: JPA, then Tomcat on :8080 An applied migration is history
Flyway keeps a checksum of every script it ran: editing an applied script makes the next start fail its validation. Change the schema with a new V…__….sql script.
3. Code
Let's go code the implementation of the Account microservice, which consists of a lot of classes. The resulting directory structure will look like this:
📁 api/
├── 📁 account/
├── 📁 account-service/
│ ├── 📁 src/
│ │ └── 📁 main/
│ │ ├── 📁 java/
│ │ │ └── 📁 store/
│ │ │ └── 📁 account/
│ │ │ ├── Account.java
│ │ │ ├── AccountServiceApplication.java
│ │ │ ├── AccountModel.java
│ │ │ ├── AccountParser.java
│ │ │ ├── AccountRepository.java
│ │ │ ├── AccountResource.java
│ │ │ └── AccountService.java
│ │ └── 📁 resources/
│ │ ├── 📁 db/
│ │ │ └── 📁 migration/
│ │ │ ├── V2026.08.24.001__create_schema.sql
│ │ │ └── V2026.08.24.002__create_table.sql
│ │ └── application.yaml
│ └── pom.xml
└── compose.yaml
Where, respecting the clean architecture, we have the following classes:
| Class | Description |
|---|---|
Account | This class represents the Account entity, which is the main entity of the Account microservice. It contains the attributes of the Account entity, such as id, name, email, password (the raw value, only on the way in), and hashPassword. |
AccountModel | This class is the JPA entity mapped to the table accounts.accounts (id, name, email, hash_password). Its constructor AccountModel(Account) and its method to() convert between the entity and the model. |
AccountParser | This class is responsible for parsing the input and output of the API endpoints, converting the AccountIn and AccountOut DTOs to the Account entity, and vice versa. |
AccountRepository | This interface is responsible for the data persistence of the Account entity, using an Object-Relational Mapping (ORM) framework to interact with the database. It extends CrudRepository and redeclares findAll() to return a List instead of an Iterable. |
AccountResource | This class is responsible for the API endpoints of the Account microservice, implementing the AccountController interface defined in the account module, and using the AccountService to handle the business logic of the API endpoints. |
AccountService | This class is responsible for the business logic of the Account microservice, using the AccountRepository to handle the data persistence of the Account entity, and the AccountParser to handle the parsing of the input and output of the API endpoints. |
Source
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
The business rules live in AccountService:
createanswers400 Bad Requestwhen the password is missing or shorter than 6 characters, or when the email is empty; otherwise it stores only the SHA-256 hash (Base64) of the password, inhash_password— never the password itself.findByIdreturnsnullfor an unknown id, andAccountResourceturns it into404 Not Found.
flowchart TB
req["POST /accounts\n(body: AccountIn)"] e1@--> p1{"password present?"}
p1 -->|"no"| r400a["400 Password is empty"]
p1 e2@-->|"yes"| p2{"6+ characters\nafter trim?"}
p2 -->|"no"| r400b["400 at least 6 characters"]
p2 e3@-->|"yes"| p3{"email not empty?"}
p3 -->|"no"| r400c["400 Email is empty"]
p3 e4@-->|"yes"| hash["hash = SHA-256 in Base64"]
hash e5@--> ins["INSERT INTO accounts.accounts"]
ins -->|"email already there\nor name missing"| r500["500: the table refuses"]
ins e6@-->|"ok"| r201["201 Created\nLocation: /accounts/(new id)"] Look at the last branch: AccountService checks the password and the email, but not the name, and it does not look for an existing email. The table does (name … NOT NULL, email … UNIQUE), and nobody maps the exception it raises, so the client gets 500 instead of 400.
The finished endpoints:
| Method | Path | Success | Errors |
|---|---|---|---|
POST | /accounts | 201 Created + Location: /accounts/{id}, no body | 400 Bad Request (password missing or short, email empty, no body); ⚠️ 500 Internal Server Error (email already in the table, name missing) |
GET | /accounts | 200 OK + list of AccountOut | — |
GET | /accounts/{id} | 200 OK + AccountOut | 404 Not Found |
DELETE | /accounts/{id} | 204 No Content, even for an unknown id | — |
GET | /accounts/health-check | 200 OK | — |
PUT | /accounts, /accounts/{id} | — | 405 Method Not Allowed: there is no update endpoint |
create builds the Location header with ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}"). The literal /accounts/health-check wins over /accounts/{id}, so a GET of health-check is never taken for an id. AccountOut has no password field: the hash never leaves the service.
Try it
Before running Docker, the same service in the browser: the simulator runs the lab's code over an empty accounts.accounts. Play or → sends the lab's requests one by one: POST returns 201 with a Location header and no body, GET /accounts lists the account without the password or its hash, a password of 3 characters gets 400 (AccountService), the same email again gets 500 (the UNIQUE of the table, not a rule of the service), PUT gets 405 (there is no update endpoint), and DELETE answers 204 even the second time. In free mode, send a body without name: AccountService lets it through and the database refuses it (500).
4. Running
To run the Account microservice, we can use the docker-compose command to start the microservice and its dependencies (e.g., the PostgreSQL database). Make sure you are in the root directory of the project, where the compose.yaml file is located, and run the following command:
Note that the --build flag is used to build the Docker images before starting the containers, which is necessary if you have made changes to the code or the Dockerfile.
Also, we can monitoring the logs of the microservice to see if it is running correctly. See there that the Flyway migrations are being executed, and that the microservice is starting up without any errors. You should see logs indicating that the microservice is up and running, and that it is connected to the database. In additional, you can also check the database to see if the migrations have been executed correctly, and that the tables have been created as expected.
-
Going inside the PostgreSQL database.
psqllives in thedbcontainer (thepostgresimage), not in the account one, so open it there with the service name fromcompose.yamland the user/database defined byDB_USERandDB_NAME(bothstore): -
Verifying the migrations:
Yet, if you want to monitor the logs of the microservice without going inside the container, you can use the docker compose logs command with the service name (account) to view the logs of the container. This will allow you to see the logs in real-time, and you can use it to monitor the startup process of the microservice, as well as any errors or issues that may arise.
Done!