【发布时间】:2021-04-15 00:45:12
【问题描述】:
我正在使用 mapstruct 将我的模型映射到我的 DTO。 我想按全名搜索记录。 我不明白为什么会出现以下错误:
Error creating bean with name 'customerController'
Error creating bean with name 'customerServiceImpl'
Error creating bean with name 'customerRepository'
No property name found for type Customer!
这是我的项目
public interface CustomerMapper {
CustomerMapper INSTANCE = Mappers.getMapper(CustomerMapper.class);
@Mapping(source = "lastName", target = "lastName")
CustomerDTO customerToCustomerDTO(Customer customer);
}
@Data
public class CustomerDTO {
private String firstName;
private String lastName;
}
@Data
@Entity
@Getter
@Setter
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String name;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CustomerListDTO {
List<CustomerDTO> categories;
}
@Controller
@RequestMapping("api/v1/customers")
public class CustomerController {
private final CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping("{name}")
public ResponseEntity<CustomerDTO> getCustomerByName(@PathVariable String name) {
return new ResponseEntity<>(
customerService.getCustomerByName(name), HttpStatus.OK
);
}
public interface CustomerRepository extends JpaRepository<Customer, Long> {
Customer findByName(String x);
}
public interface CustomerService {
CustomerDTO getCustomerByName(String name);
}
@AllArgsConstructor
@Service
public class CustomerServiceImpl implements CustomerService {
CustomerMapper customerMapper;
CustomerRepository customerRepository;
@Override
public CustomerDTO getCustomerByName(String lastName) {
return customerMapper.customerToCustomerDTO(customerRepository.findByName(lastName));
}
}
这是一个潜在的解决方法:将在 CustomerMapper 中映射以下内容,但对我来说感觉不对。
@Mapping(source = "name", target = "lastName")
@Mapping(source = "firstName", target = "firstName")
在文档中,据说您可以将模型中的任何字段映射到 DTO,我认为我的代码可能有问题。 我尝试在 repo、service、controller 中实现的方式。
编辑:
也许解决方案是在存储库中使用 DTO?
更新:
@Override
public CustomerDTO getCustomerByName(String lastName) {
return customerRepository.findByName(lastName).map(customerMapper::customerToCustomerDTO);
}
.map 无法使用。
要使用 .map 我应该使用这样的代码
.findAll()
.stream()
.map(customerMapper::customerToCustomerDTO)
.collect(Collectors.toList());
我正在使用 findByName 方法,但它无法访问 .map。
我该如何解决这个问题?
编辑
这就是我认为我的客户应该是什么样子
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CustomerDTO {
private String id;
private String firstName;
private String lastName;
}
【问题讨论】: