Paperless / rebuild
Course 2 28ef273

mappers.md

docs/mappers.md

Snapshot 28ef273Download original
1# Mappers23Pick one approach as a team and stick with it — mixing strategies within a feature leads to unmaintainable code.45## Option A: MapStruct67MapStruct generates mapper implementations from annotated interfaces:89- Define mapper interfaces with the `@Mapper` annotation.10- Use `componentModel = "spring"` so Spring registers the generated mapper as a bean.11- Use `@Mapping(source = "...", target = "...")` for any fields that do not match names directly.12- Suffix the interface with `Mapper` (e.g., `UserMapper`).13- Keep method names direction-obvious (`toDto`, `toEntity`, `toModel`).1415```java16@Mapper(componentModel = "spring")17public interface UserMapper {1819    @Mapping(source = "email", target = "emailAddress")20    UserDTO toDto(User user);2122    @Mapping(source = "emailAddress", target = "email")23    User toEntity(UserDTO userDto);24}25```2627In unit tests without a Spring context, obtain the mapper instance via `Mappers.getMapper(UserMapper.class)`.2829## Option B: Static Mappers3031Static mappers trade code generation for plain Java that can be read top-to-bottom without IDE plugins. Each feature gets two static mappers corresponding to architectural boundaries:32- `<Feature>Mapper`: static — `dto` ↔ `model`33- `persistence/mapper/<Feature>EntityMapper`: Kotlin object — `model` ↔ `entity`, called only by JPA adapters.3435### Implementation Rules36- Declare the class as `public final class`.37- Provide a `private` constructor throwing `new UnsupportedOperationException("This class should never be instantiated");`.38- Name static methods for the direction they map (`toModel`, `toEntity`, `toDto`, `fromCreateDto`, `fromUpdateDto`).39- Check for `null` at the start of each mapping method (`if (source == null) return null;`).40- Build into a local variable before returning, rather than nesting builder chains.41- Pure field mapping only: no I/O, no database calls, no service invocations inside mappers.4243```java44public final class UserMapper {4546    private UserMapper() {47        throw new UnsupportedOperationException("This class should never be instantiated");48    }4950    public static UserDTO toDto(User user) {51        if (user == null) {52            return null;53        }5455        UserDTO dto = new UserDTO(user.getId(), user.getEmail());56        return dto;57    }5859    public static User toEntity(UserDTO userDto) {60        if (userDto == null) {61            return null;62        }6364        User user = User.builder()65            .withId(userDto.id())66            .withEmail(userDto.email())67            .build();6869        return user;70    }71}72```7374Persistence adapters resolve managed associations and pass them into entity mappers; mappers perform no database access.75

Search chapters, reference and source filenames.