0

When I am trying to delete User from the users table with the help of Hibernate using its id it occurs an exception:

Caused by:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`ewp`.`user_task_history`, CONSTRAINT `FK_mkjvq9fr0e1hdgi3ekl0hluuu` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))`.

And Code:

Class User:

     @Entity
        @Table(name = "users")
        public class User implements UserDetails{
        ...
        @OneToMany(targetEntity = UserTaskHistory.class, fetch =    FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user")
        private Set<UserTaskHistory> userTaskHistories;
        ... 


Class UserTaskHistory:

    @Entity
    @Table(name = "user_task_history")
    public class UserTaskHistory{
    ...
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private User user;
    ...

The same thing happens when I'm trying to delete other objects having foreign keys. Is there any other way to make Hibernate to delete by itself all the objects that have links of foreign keys of the object I'm trying to delete?

Doron Yakovlev Golani
  • 5,188
  • 9
  • 36
  • 60
  • can you show us the transactional method where you perform the delete? – Maciej Kowalski Feb 01 '17 at 20:15
  • Take a look at [this](http://stackoverflow.com/questions/7197181/jpa-unidirectional-many-to-one-and-cascading-delete), you should find what you're looking for. – Tapaka Feb 02 '17 at 10:09

0 Answers0