简体   繁体   中英

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. Anyone please explain why I am getting Null response.

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. Try to map for each TestEntity using ModelMapper and make list of 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; in class but in dto there is no field named test_name .

Use private String testName; in TestEntity class.

Or

Use private String test_name; in TestEntityDto class.

Update use STRICT mapping and use testEntity for source.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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