Skip to content

Why my trigger is not working with Hibernate?

I have a Java spring boot project and I use Hibernate in this project. I have a void deleteAll(List<Long> idList) method and its query is @Query(value = "DELETE c FROM Course c WHERE c.id in :idList", nativeQuery = true). I want to use a trigger after every delete operation. I created a trigger in mysql and it works when I try in mysql, but it doesn’t work when I call void deleteAll(List<Long> idList) method. How can use my trigger with hibernate?

My trigger defination:

DELIMITER $$
CREATE TRIGGER after_delete_course AFTER DELETE ON course FOR EACH ROW
BEGIN
    DELETE tc1 FROM table1_course tc1 WHERE tc1.course_id = OLD.id;
    DELETE tc2 FROM table2_course tc2 WHERE tc2.course_id = OLD.id;
    DELETE tc3 FROM table3_course tc3 WHERE tc3.course_id = OLD.id;
END$$
DELIMITER ;

SQL generated by hibernate when deleteAll is called :

Hibernate: 
    DELETE c 
    FROM
        Course c 
    WHERE
        c.id in (
            ?
        )

Answer

How do you know it doesn’t work? You won’t see the delete queries of your trigger being logged in your application, this is happening only on the DBMS side. If you have an EntityManager that contains the deleted entity or the associations deleted by the trigger, you will have to detach them from the EntityManager to get a consistent view again, as Hibernate does not know what effects DML statements will have on the managed entities. Try using EntityManager.clear after executing this DML statement.