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

标签 java spring-boot spring-data-jpa modelmapper

从实体对象映射到 Dto 时,ModelMapper 在我的 DTO 字段中返回 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;
}

测试服务

@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;
    }
}

实际结果:

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

预期结果:

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

最佳答案

您正在尝试映射List<TestEntity>TestEntityDto这是错误的。 尝试为每个 TestEntity 进行映射使用 ModelMapper 并创建 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;

}

关于java - 从实体映射到 DTO 时,ModelMapper 在 DTO 字段中返回 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61290848/

相关文章:

java - 即使 Optional 包含值,Optional.orElse 的参数也会被调用

java - 使用 spring boot # SOAP Service 并行调用 SOAP 服务

java - 在所有嵌套实体中选择几个 : SPRING JPA

mysql - Spring Data JPA 通过主/外键、对象保存顺序保存一对一关系

java - 我怎样才能让这个timer()按我想要的方式工作?

java - 无论字符串大小如何,如何在 Java 中获取字符串中的最后一个字符

java - JShell 如何查找变量或结果的类型

spring-boot - SpringBootTest - 如何断言上下文加载失败

spring - 带有枚举的 QuerySyntaxException

java - Junit:测试父子实体