ModelMapper: A Cleaner Approach to Data Mapping

The Problem: Repetitive Code and Human Error

In my project, I had three key classes: AccountService, Profile, and Notification. These classes were responsible for handling data, but their code was way too repetitive. The names were so similar that I occasionally forgot to include all the necessary information or made silly mistakes. 😅 This not only slowed me down but also made debugging a nightmare.


<Before>

* AccountService.Class

*Profile.Class

*Notification.Class


The Solution: Enter ModelMapper

To tackle this, I decided to integrate ModelMapper, a fantastic library that automates object mapping and reduces boilerplate code. ModelMapper makes it super easy to map properties between objects, saving you from writing endless getters and setters. Here’s how I implemented it, step by step:


Step 1: Add ModelMapper Dependency



Step 2: Configure ModelMapper as a Bean

To avoid creating multiple instances of ModelMapper (which could lead to performance issues), I decided to register it as a Spring Bean. This way, I could inject it wherever needed without duplicating code.

Step 3: Apply ModelMapper in AccountService

I started integrating ModelMapper into my AccountService class. Instead of manually mapping fields between objects, I let ModelMapper do the heavy lifting.

Step 4: Handling Profile and Notification Classes

Here’s where I hit a small snag: my Profile and Notification classes weren’t Spring Beans, so I couldn’t directly autowire ModelMapper into them. Initially, I thought about making them Beans, but that didn’t feel right for their purpose—they were more like data models than services.

Instead, I decided to refactor my code and move the mapping logic to a controller—specifically, SettingController. This made sense because the controller was already handling requests related to profiles and notifications, and it was a Spring-managed component where I could easily inject ModelMapper.



















Comments

Popular posts from this blog

@ModelAttribute vs @RequestBody in Validation

Side Project(a self-imposed 3-day "Hackathon" challenge)

Google: The King is Back