Spring Data Jpa for循环只返回第一个数据

aemubtdh  于 2023-02-16  发布在  Spring
关注(0)|答案(1)|浏览(253)

我尝试循环遍历数据库并返回所有数据。查询返回数据库中的所有数据,但当我尝试一个接一个地循环遍历它时,它只检查第一个数据,然后终止,即使第二个或第三个数据可能为真。我不知道我犯了什么错误。

public List<CardType> getAllAvailableCardType(){
                List<CardType> cardTypeList = cardTypeRepository.findAll();
                //this method returns a list of all the cardType from the db
                //and it's working perfectly
                return cardTypeList;
            }
            public void getCards(String cardType) throws DataNotFoundException {
                String cardName = "";
                List<CardType> cardTypeList = getAllAvailableCardType();
                for (CardType cardTypes: cardTypeList){
                    //loop through the list
                    if (cardType.equalsIgnoreCase(cardTypes.getCardTypeName())){
                        //check if the entered string correspond with any of the cardTypeName in the db
                        //I have upto five cardNames stored in my db
                        //if it's true, log it in a console else through the other exception
                        
                        log.info("Congrats, there is card with the entered name "+cardType);
                    }
                    throw new DataNotFoundException("There is no card with such name");
                }
                //the problem I am facing is that this doesn't loop through my db
                //it only check if the condition is true or not only on the first data in the db
        
            }
gcxthw6b

gcxthw6b1#

我认为这是因为您在循环中抛出了datanotfound异常,因此在IF语句中进行第一次检查后,如果不满足,则它将转到循环中抛出异常的最后一行,请尝试以下重构代码

public void getCards(String cardType) throws DataNotFoundException {
    String cardName = "";
    List<CardType> cardTypeList = getAllAvailableCardType();
    boolean found = false;
    for (CardType cardTypes: cardTypeList){
        //loop through the list
        if (cardType.equalsIgnoreCase(cardTypes.getCardTypeName())){
            //check if the entered string correspond with any of the cardTypeName in the db
            //I have upto five cardNames stored in my db
            //if it's true, log it in a console else through the other exception
            log.info("Congrats, there is card with the entered name "+cardType);
            found = true;
            break;
        }
    }
    if (!found) {
        throw new DataNotFoundException("There is no card with such name");
    }
}

相关问题