【问题标题】:JPA method findAll() from repository is null [duplicate]来自存储库的 JPA 方法 findAll() 为空 [重复]
【发布时间】:2019-07-01 19:25:32
【问题描述】:

我实现了一个存储库、一个实体和一个 POJO,我想从存储库调用 findAll() 方法,但它返回空指针异常,即使我已经填充了数据库。问题是 repo 为空,而不是执行 select 后的列表。 谁能帮帮我?

这是我的仓库:

 @Repository
 public interface UpcomingMatchesFactsRepository  extends 
 CrudRepository<UpcomingMatchesFacts, Integer> {

    public boolean existsByFirstPlayerName(String firstPlayerName);

    @Query(value = "" +
            "Select u " +
            "from UpcomingMatchesFacts u " +
            "order by abs(formula) desc ")
    List<UpcomingMatchesFacts> getHighestFormulaMatches();

    List<UpcomingMatchesFacts> findAll();
}

这是我的实体:

@Entity
@Table(name = "upcomingmatchesfacts")
public class UpcomingMatchesFacts {

    public UpcomingMatchesFacts(String firstPlayerName, String secondPlayerName, int matchesWonFirstPlayer,
                                int matchesWonSecondPlayer, int currentRankFirstPlayer, int currentRankSecondPlayer,
                                int ageFirstPlayer, int ageSecondPlayer, double formula) {
        this.firstPlayerName = firstPlayerName;
        this.secondPlayerName = secondPlayerName;
        this.matchesWonFirstPlayer = matchesWonFirstPlayer;
        this.matchesWonSecondPlayer = matchesWonSecondPlayer;
        this.currentRankFirstPlayer = currentRankFirstPlayer;
        this.currentRankSecondPlayer = currentRankSecondPlayer;
        this.ageFirstPlayer = ageFirstPlayer;
        this.ageSecondPlayer = ageSecondPlayer;
        this.formula = formula;
    }

这是我要使用该方法的类:

@EnableJpaRepositories
public class ChooseBestMatches {

    @Autowired
    private UpcomingMatchesFactsRepository upcomingMatchesFactsRepository;


    public void addBestMatchesToDatabase() {
        List<UpcomingMatchesFacts> upcomingMatchesFacts = Lists.newArrayList(upcomingMatchesFactsRepository.findAll());

                //upcomingMatchesFactsRepository.getHighestFormulaMatches().subList(0, 9);

        }
    }

【问题讨论】:

    标签: spring jpa crud


    【解决方案1】:

    如果你想将spring bean注入到其他类中,它也必须是一个spring bean。在 ChooseBestMatches 类上使用 @Service 注解。

    建议:@EnableJpaRepositories 应该在配置类上,而不是在服务上。 实体必须有 noarg 构造函数。

    【讨论】:

    • 我做了更改,但我得到了同样的错误:(
    • 能否将堆栈跟踪复制到 pastebin 并在此处链接?
    猜你喜欢
    • 2018-01-02
    • 2021-09-03
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 2019-04-06
    • 1970-01-01
    • 2019-07-24
    相关资源
    最近更新 更多