从实体对象映射到 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/