FindByObject返回null,即使记录在数据库中。

huangapple go评论55阅读模式
英文:

FindByObject returns null even when record is in the db

问题

在Spring Boot应用程序中,您创建了一个名为Game的实体,其中包含一个卡片列表,该列表被转换为一个大字符串。这个Game与一个Player相关联。但当您尝试查找某个Player的Game时,Spring Boot Hibernate应用程序返回了NULL。您想要创建一个端点来显示玩家的游戏,但一直无法让它工作,已经寻找解决方案几天了。您的测试显示了玩家和其对应的game_ids,但当您尝试使用FindByPlayer时,存储库返回null。控制台显示了一些调试信息,但postman返回了[ null ]。

您提供了Game和Player的实体类、GameRepository、GamesService、GamesController以及PlayerService的代码。这些类之间的关系比较复杂,问题可能出在多个地方。您需要仔细检查以下几点:

  1. 关系映射: 确保Game和Player之间的关系正确映射。在Game实体类中,有一个与Player实体的关系,而在Player实体中,也有一个与Game实体的关系。这些关系的映射和维护需要正确配置。

  2. GameRepository的查询方法: 检查GameRepository中的findByPlayer方法是否正确实现。它应该能够根据玩家查找游戏。确保关系和查询方法的配置正确。

  3. 事务管理: 检查事务管理是否正确配置。在Game和Player的相关操作中,确保事务在需要的地方启动和提交。

  4. 日志和调试: 您已经在控制台中显示了一些调试信息,但可能需要更详细的日志来跟踪代码执行的情况,以找出问题所在。确保日志级别适当,以便在需要时记录更多信息。

  5. 异常处理: 检查是否存在异常处理机制,以便能够捕获和处理可能出现的异常情况,而不仅仅是返回null。

综上所述,问题可能出在实体关系映射、存储库查询方法、事务管理、日志和异常处理等多个方面。您需要逐一检查这些方面,以找出为什么无法正确查找某个Player的Game。

英文:

In a springboot application I create a Game, with a list-of-cards converted in a large String.
The Game is related to a Player.

When I try to lookup the Game for a Player, the Springboot Hibernate app returns NULL . Why??!??

Now I want to create an endpoint to show a players game.
I cannot get it working, looking for a solution for days now...

The test I wrote shows the players, with game_ids, but when I try to FindByPlayer, the repository returns: null

The console shows:

=====================1
player = Player [id=234, game=Game [id=232, gameCards=nl.hu.bep2.casino.blackjack.domain.GameCards@c5092df, gameState=playing,  numberOfDecks=1], user=nl.hu.bep2.casino.security.domain.User@1837c802]
=====================2
2023-02-17 18:33:45.333 DEBUG 2216 --- [nio-8080-exec-3] org.hibernate.SQL                        : select game0_.id as id1_2_, game0_.current_move as current_2_2_, game0_.game_cards as game_car3_2_, game0_.game_state as game_sta4_2_, game0_.number_of_decks as number_o5_2_ from game game0_ left outer join player player1_ on game0_.id=player1_.game_id where player1_.id=?
====================3
player =Player [id=234, game=Game [id=232, gameCards=nl.hu.bep2.casino.blackjack.domain.GameCards@c5092df, gameState=playing,  numberOfDecks=1], user=nl.hu.bep2.casino.security.domain.User@1837c802]
speler:   234  heeft geen game

and postman shows:[ null ]

I use the following Classes:

Game

@Transactional
@Entity
@JsonIgnoreProperties({"player","dealer"})
public class Game {
	
	@Id
    @GeneratedValue
	private long id;
	 
	@Convert(converter = CardListConverter.class)
	@Column(length = 20000)
	private GameCards gameCards;
    
    @Enumerated(EnumType.STRING)
	private GameState gameState;
  
	@OneToOne(mappedBy="game", cascade = CascadeType.ALL)  
	private Player player;
	
    @OneToOne(mappedBy="game", cascade = CascadeType.ALL)
	private Dealer dealer;
    
	private Move current_move;
	
	private Integer numberOfDecks;
	
	public Game() {
		
	}

Player

@Transactional
@Entity
@JsonIgnoreProperties("game")
public class Player extends Hand implements Serializable{

	@Id
	@GeneratedValue
	private long id;
	//@JsonManagedReference
	@OneToOne(fetch=FetchType.EAGER)
	@JoinColumn(name="game_id")
	private Game game;

	@ManyToOne(fetch = FetchType.EAGER)
	private User user;    // niet via id koppelen aan een object, user heeft de link naar gepersisteerde chips. dit private object wordt in de applicatielaag gevuld met de chips van de user
							//dependency injection van chips in player in applicatielaag, blackjackservice, startgame

	public Player(){
	}	
	
	public Player(User user, Game game) {
		super();
		this.user = user;
		this.game=game;
		
	}
	

GameRepository

public interface GameRepository  extends JpaRepository<Game, Long>{
	Game findByPlayer(Player player);
}

GamesService

@Service
public class GamesService {
	
	@Autowired
	private GameRepository gameRepository;
	@Autowired
	private UserService userService;
	@Autowired
	private PlayerService playerService;
	
	
	public GamesService(){
	}

	
		public List<Game> GetGamesByUsername(String username) {
		
		List<Game> gameList = new ArrayList<>();
		List<Player> players = this.playerService.GetPlayerByUsername(username); 
        
        for
		  ( Player p : players) { 
          System.out.println("=====================1");
		  System.out.println("player = "+ p);
		  System.out.println("=====================2");
		  
		  Game game = this.gameRepository.findByPlayer(p);
		  gameList.add(game);
		  System.out.println("====================3"); System.out.println("player ="+
		  p);
		  
		  if (game != null) { System.out.println("speler:   "+ p.getId() +
		  "  /n vinden we game " + game.getId()); }else{
		  System.out.println("speler:   "+ p.getId() + "  heeft geen game"); }
		  	  
	    }    
		return gameList;		
	}
}

GamesController

@RestController
@RequestMapping("/game")
public class GamesController {
	
	private final GamesService service;
	// SameService injecteren, en service noemen
	public GamesController(GamesService service) {
		this.service = service;
	}
	
	@PostMapping("/showgames")
	@ResponseBody
	public List<Game> getGames(Authentication authentication, UserService userService){
		UserProfile profile = (UserProfile) authentication.getPrincipal();
		
	 try {
		 	List<Game> gameList = new ArrayList<>();
		 	String username = profile.getUsername();
 	
			gameList = this.service.GetGamesByUsername(username);
			
	        return gameList;
	            
	        } catch (NegativeNumberException exception) {
	            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, exception.getMessage());
	        }
	}
}

Also there is a User connected to the player, that works fine
Playerservice works fine:

@Service
public class PlayerService {
	
	@Autowired
	private PlayerRepository playerRepository;
	@Autowired
	private UserService userService;


	public List<Player> GetPlayerByUsername(String username) {
		
		User user = userService.loadUserByUsername(username);
		List<Player> players = playerRepository.findByUser(user);        
		
		return players;
	}

答案1

得分: 1

如果玩家具有game_id,那么您可以尝试按如下所示的方式通过id查找游戏:

public interface GameRepository extends JpaRepository<Game, Long> {
    Optional<Game> findById(Long id);
}

然后将player.getGameId()传递给存储库,而不是玩家。

英文:

If player has game_id, then you may try to reach Game by id as shown below:

public interface GameRepository extends JpaRepository&lt;Game, Long&gt;{
    Optional&lt;Game&gt; findById(Long id);
}

Then pass the player.getGameId() to the repository instead of Player.

huangapple
  • 本文由 发表于 2023年2月18日 01:50:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487678.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定