I have a bidirectional ManyToMany mapping, and I am trying to delete a post entity. When I delete it, the reference in the posts_categories table should also be removed. However, despite trying the following two approaches, it’s not deleting the reference, and I am receiving the error below. I am using postgresql and I did not find solution for my problem.
ERROR: The UPDATE or DELETE operation on the "posts" table violates the "fkq4402eed597exuj50g73c7kmg" foreign key constraint on the "posts_categories" table.
First Approach
@Entity
@Data
@Table(name = "posts")
public class PostEntity extends BaseEntity {
@ManyToMany
@JoinTable(
name = "posts_categories",
joinColumns = {@JoinColumn(name = "post_id")},
inverseJoinColumns = {@JoinColumn(name = "category_id")})
private Set<CategoryEntity> categories = new HashSet<>();
...
}
@Entity
@Data
@Table(name = "categories")
public class CategoryEntity extends BaseEntity {
@ManyToMany(mappedBy = "categories")
private Set<PostEntity> posts = new HashSet<>();
}
Second Approach
@Entity
@Data
@Table(name = "posts")
public class PostEntity extends BaseEntity {
@ManyToMany
@JoinTable(
name = "posts_categories",
joinColumns = {@JoinColumn(name = "post_id")},
inverseJoinColumns = {@JoinColumn(name = "category_id")})
private Set<CategoryEntity> categories = new HashSet<>();
...
}
@Entity
@Data
@Table(name = "categories")
public class CategoryEntity extends BaseEntity {
@ManyToMany
@JoinTable(
name = "posts_categories",
joinColumns = {@JoinColumn(name = "category_id")},
inverseJoinColumns = {@JoinColumn(name = "post_id")})
private Set<PostEntity> posts = new HashSet<>();
}
My Service:
@Transactional
public Boolean deleteByUUID(UUID uuid) {
Entity entity = postRepository.findByUuid(uuid).orElse(null);
if (entity != null) {
postRepository.delete(entity);
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
}
2
Answers
It turns out the issue was due to the @Data annotation, which was causing an infinite loop in the background, likely due to the toString, hashCode, and equals methods —or possibly just the toString method alone; I'm not entirely sure.
To resolve the issue, I removed the @Data annotation and implemented the getter and setter methods manually, which fixed the problem.
in addition, from my research, it appears that using a bulk remove method is more efficient in many-to-many relationships from a performance standpoint. Normally, Hibernate sends multiple queries for the deletion process, which can lead to performance issues. Therefore, it’s recommended to manually write a single delete query to improve performance in these cases.
U can try to make foreign relation with both tables and when u delete relation from table where is exists many to many relation, u can easily see that in both tables matched rows are deleted