0

I want to create a first table question and second table reponse which has a reference on question by question_id.

I have this two Pojos ;

@Entity
public class Question implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Long id;
    protected String texte;

@Entity
public class Reponse implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Long id;

    @ManyToOne
    @JoinColumn(name = "question_id")
    private Question question;

I create the table like this :

CREATE TABLE question (
    id INT AUTO_INCREMENT PRIMARY KEY,
    texte VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE reponse (
    id INT AUTO_INCREMENT PRIMARY KEY,
    texte VARCHAR(255) NOT NULL,
    question_id INT REFERENCES question(id) ON DELETE CASCADE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

And then I added somes values into it :

INSERT INTO question (id, texte) VALUES (0, "Quel sont les trois grands principes de la POO ?");
INSERT INTO question (id, texte) VALUES (1, "Quel interface implémente la classe ArrayList ?");

INSERT INTO reponse (texte, question_id) VALUES ("L'encapsulation, l'héritage et le polymorphisme.", 0);
INSERT INTO reponse (texte, question_id) VALUES ("L'encapsulation, l'héritage multiple et le polymorphisme.", 0);
INSERT INTO reponse (texte, question_id) VALUES ("Le multi-threading, l'accès aux données et le polymorphisme.", 0);

INSERT INTO reponse (texte, question_id) VALUES ("List", 1);
INSERT INTO reponse (texte, question_id) VALUES ("Queue", 1);
INSERT INTO reponse (texte, question_id) VALUES ("Serializable", 1);

Finally, when I tried to do :

EntityManagerFactory emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, ConfigReader.getProperties("/db.properties"));

I get this stack :

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "alter table Reponse add constraint FKgdr6si626nqixg8qyfx6s0pjl foreign key (question_id) references Question (id)" via JDBC Statement

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`quizz`.`#sql-145c_e3`, CONSTRAINT `FKgdr6si626nqixg8qyfx6s0pjl` FOREIGN KEY (`question_id`) REFERENCES `question` (`id`))

What does "Cannot add or update a child row" means ?

jozinho22
  • 459
  • 2
  • 7
  • 24

0 Answers0