我正在尝试创建一个投注API,现在我发现了一种使用Mapper最大限度地减少代码返工的方法,但我不明白代码中存在的问题。
错误:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 1 of constructor in api.loteria.loteriaapi.services.Mysql.BetServiceMysql required a bean of type 'api.loteria.loteriaapi.dtos.mappers.BetMapper' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'api.loteria.loteriaapi.dtos.mappers.BetMapper' in your configuration.
BetMapper.Java
@Mapper(componentModel = "spring")
public interface BetMapper {
@Mapping(target = "bet.id", source = "betId")
Bet betResquetToEntity(BetRequest betRequest);
@Mapping(source = "bet.id", target = "betId")
BetResponse entityToBetResponse(Bet bet);
}
BetServiceMysql.java
@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class BetServiceMysql implements BetService {
private BetRepository betRepository;
private BetMapper betMapper;
@Override
public List<BetResponse> list() {
List<Bet> bets = betRepository.findAll();
return bets.stream().map(bet -> betMapper.entityToBetResponse(bet)).collect(Collectors.toList());
}
@Override
public BetResponse save(BetRequest betRequest) {
Bet bet = betMapper.betResquetToEntity(betRequest);
try {
betRepository.save(bet);
}catch(RuntimeException e){
throw new DataIntegrityViolationException(e.getMessage());
}
return betMapper.entityToBetResponse(bet);
}
@Override
public BetResponse update(Long id, BetRequest betRequest) {
Bet bet = verifyIfExist(id);
updateData(bet, betRequest);
betRepository.save(bet);
return betMapper.entityToBetResponse(bet);
}
@Override
public BetResponse delete(Long id) {
Bet bet = verifyIfExist(id);
betRepository.delete(bet);
return betMapper.entityToBetResponse(bet);
}
@Override
public BetResponse getBetById(Long id) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<BetResponse> getBets() {
// TODO Auto-generated method stub
return null;
}
protected Bet verifyIfExist(Long id){
return betRepository.findById(id).orElseThrow(() -> new EntityNotFoundException(String.format("ID: %s || Não foi encontrado nenhuma entidade para o id fornecido", id)));
}
protected void updateData(Bet bet, BetRequest betRequest){
bet.setMaxNumbersByUsers(betRequest.getMaxNumbersByUsers());
}
}
BetService.java
public interface BetService {
List<BetResponse> list();
BetResponse save(BetRequest betRequest);
BetResponse update(Long id, BetRequest betRequest);
BetResponse delete(Long id);
BetResponse getBetById(Long id);
List<BetResponse> getBets();
}
我尝试从Mapper中删除@Autowired,代码运行,但当插入新赌注时,Mapper出现另一个错误,即为空
2条答案
按热度按时间b91juud31#
尝试将@Component注解添加到您的BetMapper类。
jei2mxaa2#
1.看起来Mapper现在不工作。我不确定,但看起来这里的用法不正确,
betResquetToEntity
中没有参数bet
,而@Mapping(target = "bet.id", source = "betId")
应该是@Mapping(target = "id", source = "betRequest.betId")
1.检查
mapstruct-processor
是否已添加到plugin
部分link中的maven-compiler-plugin