Skip to content

Implement Automatic DTO Mapping Feature... #3618

Closed as not planned
Closed as not planned
@Mouon

Description

@Mouon

Implement Automatic DTO Mapping Feature

I am leaving an issue to learn from great people 🙏🏻 🙏🏻 🙏🏻

Issue

Implement Automatic DTO Mapping Feature
Description:
We need a feature to automatically convert entity lists obtained from @query into DTOs. The goal is to add logic that uses reflection to automatically map values from entity fields to DTO fields with the same names.
Objectives:

Implement a method for automatic mapping from entities to DTOs
Use reflection for field mapping Handle exceptions for mapping failures

Sample Code:

import ...

public class AutoMapper {
    @Nullable
    public static <D, E> D mapEntityToDto(Class<D> dtoClass, @Nullable E entity,
                                          MappingContext<? extends PersistentEntity<?, ?>, ? extends PersistentProperty<?>> mappingContext) throws Exception {
        Assert.notNull(dtoClass, "DTO class must not be null");
        Assert.notNull(mappingContext, "MappingContext must not be null");
        
        if (entity == null) {
            return null;
        }
        
        Constructor<D> constructor = dtoClass.getConstructor();
        D dtoInstance = constructor.newInstance();
        
        PersistentEntity<?, ?> persistentEntity = mappingContext.getPersistentEntity(entity.getClass());
        if (persistentEntity instanceof JpaPersistentEntity) {
            JpaPersistentEntity<?> jpaPersistentEntity = (JpaPersistentEntity<?>) persistentEntity;
            for (JpaPersistentProperty property : jpaPersistentEntity) {
                String propertyName = property.getName();
                Field dtoField = ReflectionUtils.findField(dtoClass, propertyName);
                if (dtoField != null) {
                    ReflectionUtils.makeAccessible(dtoField);
                    Object value = property.getGetter().invoke(entity);
                    ReflectionUtils.setField(dtoField, dtoInstance, value);
                }
            }
        }
        
        return dtoInstance;
    }
}

Benefits

Simplifies mapping process

Can be used with @query annotations, e.g.

@Query("SELECT new com.server.dto.gitHubIssue.GithubIssueListResponse$GithubIssue")

Note for Reviewers

I'm new to this and would greatly appreciate any guidance or suggestions for improvement. Thank you for your time and expertise! 🙏🏻

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions