Nguyên nhân có thể là do hibernate vẫn đang quản lý parent-children trong context của nó ở đâu đó, khiến khi lưu parent lại lưu lại children.
Em thử gọi thêm parentRepository.save(parent); xem sao.
Ngoài ra:
Đầu tiên, đừng bao giờ dùng mấy cái annotation @OneToMany, trong thực tế dữ liệu rất nhiều nó có thể gây sập server.
Thứ 2. Đừng bao giờ gọi kiểu này List<B> existingChildren = childRepository.findByParentId(aId); nó lấy rất tất cả bản ghi liên quan cũng có thể gây sập server. hãy dùng jpql kiểu này:
public interface ChildRepository extends JpaRepository<B, Long> {
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("""
DELETE FROM B child
WHERE child.parent.id = :parentId
AND child.id IN :deleteIds
""")
int deleteByParentIdAndIds(
@Param("parentId") Long parentId,
@Param("deleteIds") Collection<Long> deleteIds
);
}
@Transactional
public void deleteChildren(Long parentId, Collection<Long> deleteIds) {
if (deleteIds == null || deleteIds.isEmpty()) {
return;
}
if (!parentRepository.existsById(parentId)) {
throw new EntityNotFoundException(
"Parent not found: " + parentId
);
}
int deletedCount = childRepository.deleteByParentIdAndIds(
parentId,
deleteIds
);
if (deletedCount != deleteIds.size()) {
throw new IllegalArgumentException(
"One or more child IDs do not belong to parent: " + parentId
);
}
}