Eu tenho duas tables, uma PLAYER e uma HERO.
As PLAYER é de um jogador de RPG e a HERO é do personagem.
Eu to fazendo um CRUD em Java mas não to conseguindo fazer o método Include do HERO por que da o erro:
Cannot add or update a child row: a foreign key constraint fails (rpg
.hero
, CONSTRAINT hero_ibfk_1
FOREIGN KEY (PlayerID
) REFERENCES player
(Playerid
))
Classe Hero:
public class Hero {
private int HeroId;
private String HeroName;
private int level;
private int strenght;
private int hp;
private int speed;
private Player playerID;
private RacesEnum heroRace;
Classe Player:
public class Player {
private int playerId;
private String playerName;
O include do Hero:
ublic void include(Hero character) throws SQLException {
String sql = "INSERT INTO Hero(HeroName, level, strenght, hp, speed, playerId, HeroRace) VALUES(?, ?, ?, ?, ?, ?, ?)";
try(PreparedStatement pstm = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)){
pstm.setString(1, character.getCharName());
pstm.setInt(2, character.getLevel());
pstm.setInt(3, character.getStrenght());
pstm.setInt(4, character.getHp());
pstm.setInt(5, character.getSpeed());
pstm.setInt(6, character.getPlayer().getPlayerId());
pstm.setString(7, character.getCharRace().toString());
pstm.execute();
try(ResultSet rst = pstm.getGeneratedKeys()){
while(rst.next()) {
character.setCharId(rst.getInt(1));
}
}
}
}
E a classe teste:
public class testeCharacter {
public static void main(String[] args) throws SQLException {
ConnectionFactory factory = new ConnectionFactory();
Connection connection = factory.recuperarConexao();
Player p1 = new Player("Thiago");
PlayerDAO pDAO = new PlayerDAO(connection);
Hero h1 = new Hero("Kaaras", 1, 10, 50, 10, p1, RacesEnum.ELF);
HeroDAO hDAO = new HeroDAO(connection);
// pDAO.include(p1);
hDAO.include(h1);
O include do Player tá indo sem erro.
Table do Player:
Table do Hero: