Reputation: 533
I get the error
Cannot delete or update a parent row: a foreign key constraint fails (`gestion_ejercicios_programacion`.`examen`, CONSTRAINT `examen_ibfk_1` FOREIGN KEY (`titulacionID`) REFERENCES `titulacion` (`id`))
when trying to delete an entity with hibernate. Here's what I'm trying to do in my main:
TitulacionDAO tDAO = context.getBean(TitulacionDAO.class);
Titulacion t1 = new Titulacion("titulacion 1");
tDAO.save(t1);
ExamenDAO exDAO = context.getBean(ExamenDAO.class);
Examen ex1 = new Examen(3, 11, "examen 1", t1);
exDAO.save(ex1);
tDAO.delete(t1);
Here's Examen mapping for my Titulacion
@ManyToOne(cascade=CascadeType.PERSIST)
@JoinColumn(name="titulacionID", referencedColumnName="id")
private Titulacion titulacion;
and here's my Titulacion mapping for Examen
@OneToMany(cascade=CascadeType.REMOVE, mappedBy="titulacion", orphanRemoval=true)
private Set<Examen> examenes = new HashSet<>();
This is my database:
CREATE TABLE examen (
id INT AUTO_INCREMENT PRIMARY KEY,
mes INT(2),
ano INT(4),
descripcion VARCHAR(1000),
titulacionID INT,
FOREIGN KEY (titulacionID) REFERENCES titulacion(id)
);
CREATE TABLE titulacion (
id INT AUTO_INCREMENT PRIMARY KEY PRIMARY KEY,
nombre VARCHAR(100)
);
I have no idea why this is happening, I've read several posts on this topic and from what I've read this should be working. Thanks for the help
Upvotes: 0
Views: 37
Reputation: 691715
You didn't add the examen to the Titulacion. So when deleting the titulacion, Hibernate doesn't know that the examen need to be deleted too
Upvotes: 1