简体   繁体   English

ModelMapper 在从实体映射到 DTO 时在 DTO 字段中返回 Null

[英]ModelMapper return Null in DTO fields while mapping from Entity to DTO

ModelMapper returns null in my DTO fields while mapping from Entity Object to Dto.当从实体 Object 映射到 Dto 时, null在我的 DTO 字段中返回 null。 Anyone please explain why I am getting Null response.任何人请解释为什么我收到Null响应。

TestEntity

@Data
@Entity
@Table(name="TestEntity")
public class TestEntity {
    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name="test_name")
    private String test_name;
}

TestEntityDto

@Data
public class TestEntityDto {

    private long id;
    private String test_name;
}

TestService

@Service
public class TestService {

    @Autowired
    TestEntityRepo testEntityRepo;

    public TestEntityDto getAllTestList() {
        List<TestEntity> testEntity= testEntityRepo.findAll();
        ModelMapper mapper = new ModelMapper();
        TestEntityDto testEntityDto = mapper.map(TestEntity.class, TestEntityDto.class);

        return  testEntityDto;
    }
}

Actual Result:实际结果:

{
   "id": 0,
   "test_name": null
}

Expected Result:预期结果:

{
   "id": 1,
   "test_name": "Test"
}

You are trying to map List<TestEntity> to TestEntityDto which is wrong.您正在尝试 map List<TestEntity>TestEntityDto这是错误的。 Try to map for each TestEntity using ModelMapper and make list of TestEntityDto .尝试使用 ModelMapper 为每个TestEntity map 并列出TestEntityDto

public List<TestEntityDto> getAllTestList() {

    List<TestEntity> testEntity= testEntityRepo.findAll();
    List<TestEntityDto> testEntityDtos = new ArrayList<TestEntityDto>();
    ModelMapper mapper = new ModelMapper();
    mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
    for(TestEntity perTestEntity :testEntity){
        TestEntityDto testEntityDto = mapper.map(perTestEntity , TestEntityDto.class);
         testEntityDtos.add(testEntityDto);
    }
    return  testEntityDtos;

}

You are using private String test_name;您正在使用private String test_name; in class but in dto there is no field named test_name .在 class 但在 dto 中没有名为test_name的字段。

Use private String testName;使用private String testName; in TestEntity class.TestEntity

Or或者

Use private String test_name;使用private String test_name; in TestEntityDto class.TestEntityDto到 class。

Update use STRICT mapping and use testEntity for source.更新使用STRICT映射并使用 testEntity 作为源。

ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
TestEntityDto testEntityDto = mapper.map(testEntity, TestEntityDto.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM