MapStruct用于具有不同数据类型的类

huangapple go评论71阅读模式
英文:

MapStructs for classes with different data types

问题

以下是您要翻译的部分:

"我对mapstructs还很陌生,但我想要映射这两个类结构。

目标类:

@Data
class Student{
    private PersonalInfo personalInfo;
    private List<Academic> academics;
}

@Data
class PersonalInfo{
   private String name;
   private String address;
}

@Data
class Academic{
   private String subject;
   private String score;
   private String grade;
}

DTO类如下,
源代码:

class StudentDTO{
    private PersonalDTO personal;
    private List<AcademicDTO> academics;
}

class PersonalDTO{
   private String name;
   private String address;
}

class AcademicDTO{
   private String subject;
   private Double score;
   private Long grade;
}

我已经成功将PersonalDTO类映射到PersonalInfo,但无法将AcademicDTO映射到Academic(因为Academic中的所有数据类型都是String,而AcademicDTO包含Double和Long)。

请有人帮我创建一个Student映射器,将PersonalDto映射到Personal和AcademicDto映射到Academic。谢谢。"

英文:

I am new to mapstructs, and I wanted to map these two class structures

Target classes:

@Data
class Student{
    private PersonalInfo personalInfo;
    private List&lt;Academic&gt; academics;
}

@Data
class PersonalInfo{
   private String name;
   private String address;
}

@Data
class Academic{
   private String subject;
   private String score;
   private String grade;
}

and the DTO classes are as follows,
Source:


class StudentDTO{
    private PersonalDTO personal;
    private List&lt;AcademicDTO&gt; academics;
}

class PersonalDTO{
   private String name;
   private String address;
}

class AcademicDTO{
   private String subject;
   private Double score;
   private Long grade;
}

I was able to map PersonalDTO class to PersonalInfo but not AcademicDTO to Academic(as all the data types in Academic are String and AcademicDTO has Double and Long).

Can someone please help me create a Student mapper which maps PersonalDto to Personal and AcademicDto to Academic. Thanks.

答案1

得分: 1

以下是您要求的代码部分的翻译:

POJOs

@Data
@Builder
public class Academic {
    
    private String subject;
    private String score;
    private String grade;
    
}

@Data
@Builder
public class PersonalInfo {
    
    private String name;
    private String address;
    
}
@Value
public class StudentDTO {
    
    PersonalDTO personal;
    List<AcademicDTO> academics;
    
}

@Value
public class PersonalDTO {
    
    String name;
    String address;
    
}

@Value
public class AcademicDTO {
     
     String subject;
     Double score;
     Long grade;
     
}

Mapper

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper(componentModel = "spring")
public interface StudentMapper {

    @Mapping(target = "personal", source = "personalInfo")
    StudentDTO toDTO(Student student);

}

Mapper Test

import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;
import org.junit.jupiter.api.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

class StudentMapperTest {

    private final StudentMapper studentMapper = new StudentMapperImpl();

    @Test
    void toDTO() {
        // Arrange
        final Student student = Student.builder()
                .personalInfo(PersonalInfo.builder()
                        .name("John Doe")
                        .address("123 Main Street, New York, NY 10030")
                        .build())
                .academics(List.of(
                        Academic.builder()
                                .subject("Math")
                                .score("100")
                                .grade("1")
                                .build(),
                        Academic.builder()
                                .subject("Science")
                                .score("90")
                                .grade("2")
                                .build()
                ))
                .build();

        // Act
        final StudentDTO studentDTO = studentMapper.toDTO(student);

        // Assert
        assertThat(studentDTO.getPersonal()).usingRecursiveComparison().isEqualTo(student.getPersonalInfo());
        assertThat(studentDTO.getAcademics())
                .usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration.builder()
                        .withEqualsForFields((a, b) -> Double.parseDouble(a.toString()) == Double.parseDouble(b.toString()), "score")
                        .withEqualsForFields((a, b) -> Long.parseLong(a.toString()) == Long.parseLong(b.toString()), "grade")
                        .build())
                .isEqualTo(student.getAcademics());
    }
    
}

Generated Mapper Impl

@Component
public class StudentMapperImpl implements StudentMapper {

    @Override
    public StudentDTO toDTO(Student student) {
        if ( student == null ) {
            return null;
        }

        PersonalDTO personal = null;
        List<AcademicDTO> academics = null;

        personal = personalInfoToPersonalDTO( student.getPersonalInfo() );
        academics = academicListToAcademicDTOList( student.getAcademics() );

        StudentDTO studentDTO = new StudentDTO( personal, academics );

        return studentDTO;
    }

    protected PersonalDTO personalInfoToPersonalDTO(PersonalInfo personalInfo) {
        if ( personalInfo == null ) {
            return null;
        }

        String name = null;
        String address = null;

        name = personalInfo.getName();
        address = personalInfo.getAddress();

        PersonalDTO personalDTO = new PersonalDTO( name, address );

        return personalDTO;
    }

    protected AcademicDTO academicToAcademicDTO(Academic academic) {
        if ( academic == null ) {
            return null;
        }

        String subject = null;
        Double score = null;
        Long grade = null;

        subject = academic.getSubject();
        if ( academic.getScore() != null ) {
            score = Double.parseDouble( academic.getScore() );
        }
        if ( academic.getGrade() != null ) {
            grade = Long.parseLong( academic.getGrade() );
        }

        AcademicDTO academicDTO = new AcademicDTO( subject, score, grade );

        return academicDTO;
    }

    protected List<AcademicDTO> academicListToAcademicDTOList(List<Academic> list) {
        if ( list == null ) {
            return null;
        }

        List<AcademicDTO> list1 = new ArrayList<AcademicDTO>( list.size() );
        for ( Academic academic : list ) {
            list1.add( academicToAcademicDTO( academic ) );
        }

        return list1;
    }
}

请注意,我已经去除了您原始文本中的HTML编码,以便更清晰地显示代码。

英文:

The following works for me.
Did you maybe forget the setters on the DTOs?

POJOs

@Data
@Builder
public class Academic {
    
    private String subject;
    private String score;
    private String grade;
    
}

@Data
@Builder
public class PersonalInfo {
    
    private String name;
    private String address;
    
}

@Data
@Builder
public class Academic {
    
    private String subject;
    private String score;
    private String grade;
    
}

DTOs

@Value
public class StudentDTO {
    
    PersonalDTO personal;
    List&lt;AcademicDTO&gt; academics;
    
}

@Value
public class PersonalDTO {
    
    String name;
    String address;
    
}

@Value
public class AcademicDTO {
     
     String subject;
     Double score;
     Long grade;
     
}

Mapper

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper(componentModel = &quot;spring&quot;)
public interface StudentMapper {

    @Mapping(target = &quot;personal&quot;, source = &quot;personalInfo&quot;)
    StudentDTO toDTO(Student student);

}

Mapper Test

import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;
import org.junit.jupiter.api.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

class StudentMapperTest {

    private final StudentMapper studentMapper = new StudentMapperImpl();

    @Test
    void toDTO() {
        // Arrange
        final Student student = Student.builder()
                .personalInfo(PersonalInfo.builder()
                        .name(&quot;John Doe&quot;)
                        .address(&quot;123 Main Street, New York, NY 10030&quot;)
                        .build())
                .academics(List.of(
                        Academic.builder()
                                .subject(&quot;Math&quot;)
                                .score(&quot;100&quot;)
                                .grade(&quot;1&quot;)
                                .build(),
                        Academic.builder()
                                .subject(&quot;Science&quot;)
                                .score(&quot;90&quot;)
                                .grade(&quot;2&quot;)
                                .build()
                ))
                .build();

        // Act
        final StudentDTO studentDTO = studentMapper.toDTO(student);

        // Assert
        assertThat(studentDTO.getPersonal()).usingRecursiveComparison().isEqualTo(student.getPersonalInfo());
        assertThat(studentDTO.getAcademics())
                .usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration.builder()
                        .withEqualsForFields((a, b) -&gt; Double.parseDouble(a.toString()) == Double.parseDouble(b.toString()), &quot;score&quot;)
                        .withEqualsForFields((a, b) -&gt; Long.parseLong(a.toString()) == Long.parseLong(b.toString()), &quot;grade&quot;)
                        .build())
                .isEqualTo(student.getAcademics());
    }
    
}

Generated Mapper Impl

@Component
public class StudentMapperImpl implements StudentMapper {

    @Override
    public StudentDTO toDTO(Student student) {
        if ( student == null ) {
            return null;
        }

        PersonalDTO personal = null;
        List&lt;AcademicDTO&gt; academics = null;

        personal = personalInfoToPersonalDTO( student.getPersonalInfo() );
        academics = academicListToAcademicDTOList( student.getAcademics() );

        StudentDTO studentDTO = new StudentDTO( personal, academics );

        return studentDTO;
    }

    protected PersonalDTO personalInfoToPersonalDTO(PersonalInfo personalInfo) {
        if ( personalInfo == null ) {
            return null;
        }

        String name = null;
        String address = null;

        name = personalInfo.getName();
        address = personalInfo.getAddress();

        PersonalDTO personalDTO = new PersonalDTO( name, address );

        return personalDTO;
    }

    protected AcademicDTO academicToAcademicDTO(Academic academic) {
        if ( academic == null ) {
            return null;
        }

        String subject = null;
        Double score = null;
        Long grade = null;

        subject = academic.getSubject();
        if ( academic.getScore() != null ) {
            score = Double.parseDouble( academic.getScore() );
        }
        if ( academic.getGrade() != null ) {
            grade = Long.parseLong( academic.getGrade() );
        }

        AcademicDTO academicDTO = new AcademicDTO( subject, score, grade );

        return academicDTO;
    }

    protected List&lt;AcademicDTO&gt; academicListToAcademicDTOList(List&lt;Academic&gt; list) {
        if ( list == null ) {
            return null;
        }

        List&lt;AcademicDTO&gt; list1 = new ArrayList&lt;AcademicDTO&gt;( list.size() );
        for ( Academic academic : list ) {
            list1.add( academicToAcademicDTO( academic ) );
        }

        return list1;
    }
}

huangapple
  • 本文由 发表于 2023年7月18日 12:33:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76709560.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定