我是springBoot框架的新手。我想获取数据库中所有用户的电子邮件列表。但我想为此逻辑使用Dto投影。但是直到我从未使用过Dto模式。
@Override
public List<AllEmailsDto> getAllEmails() {
Iterable<EmployeeEntity> employeeEntity=employeRepository.findAll();
AllEmailsDto employeeDto=AllEmailsConverter.convertToDtoEmails(employeeEntity,new AllEmailsDto());
return null;
}
这里我得到了可迭代的对象,但是我不知道如何将employeeEntity
对象转换为dto。
public class AllEmailsDto {
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
此转换有多种方法:
1。 Model Mapper是用于对象映射的库:
首先,您需要添加新的依赖项:
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.5</version>
</dependency>
然后输入您的代码:
@Autowired
private ModelMapper modelMapper;
@Override
public List<AllEmailsDto> getAllEmails() {
Iterable<EmployeeEntity> employeeEntity = employeRepository.findAll();
return modelMapper.mapAll(employeeEntity, AllEmailsDto.class); // new line
}
首先,您需要添加一个新的依赖项:
<dependency> <groupId>ma.glasnost.orika</groupId> <artifactId>orika-core</artifactId> <version>1.4.6</version> </dependency>
然后输入您的代码:
:MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build(); @Override public List<AllEmailsDto> getAllEmails() { mapperFactory.classMap(EmployeeEntity.class, AllEmailsDto.class); MapperFacade mapper = mapperFactory.getMapperFacade(); Iterable<EmployeeEntity> employeeEntity = employeRepository.findAll(); return mapper.mapAsList(employeeEntity, AllEmailsDto.class); }
或编写您的自定义映射器
公共类AllEmailsDto {私人字符串电子邮件;
public AllEmailsDto(String email) { this.email = email; } public AllEmailsDto fromEntity(EmployeeEntity entity) { return new AllEmailsDto(entity); }
}
并且为您服务:
@Override
public List<AllEmailsDto> getAllEmails() {
Iterable<EmployeeEntity> employeeEntity = employeRepository.findAll();
return employeeEntity.stream()
.map(AllEmailsDto::fromEntity)
.collect(Collectors.toList());
}