我正在测试服务类中的方法,该方法基本上从我的存储库类中调用方法
save
:
@Repository
public interface GameManagerRepository extends JpaRepository<Game, String> {
Game findCreateGameByPublisherId(String publisherId);
}
这是我的测试方法:
@DisplayName("Test for createGame")
@Test
public void createGameTest(){
game = new Game();
game.setPublisherId("123");
game.setGameDataId("abc");
game.setName("hello world");
gameManagerRepository.save(game);
System.out.println(game);
System.out.println(game != null);
System.out.println(gameManagerRepository.findCreateGameByPublisherId("123"));
}
我确实添加了一些
System.out.println
来尝试确定我的代码到底出了什么问题,这就是结果:
Game(gameDataId=abc, publisherId=123, name=hello world, timePlayed=null)
true
null
如您所见,我在数据库中找不到该实体,也无法找出原因。
我在这里做错了什么?
我认为问题在于存储库类中方法
findCreateGameByPublisherId
的命名约定。从 JPA 中的方法名称创建查询通常遵循 findBy[AttributeName]
格式。原来如此
Game findByPublisherId(String publisherId);
或者您应该将该方法的查询显式定义为
@Query("select g from Game g where g.publisherId = ?1")
Game findCreateGameByPublisherId(String publisherId);