我有两个实体-
1.用户名
1.类别
两个实体之间存在**@ManyToMany关系**。创建此关系的代码是-
1.使用者.java
@ManyToMany(cascade = { CascadeType.DETACH, CascadeType.MERGE,
CascadeType.REFRESH }, fetch = FetchType.LAZY)
@JoinTable(name = "enrolled",
joinColumns = @JoinColumn(
name = "user",
referencedColumnName = "userid"),
inverseJoinColumns = @JoinColumn(
name = "category",
referencedColumnName = "category_id"))
List<Category> enrolledCategories=new ArrayList<>();
2.类别.java
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="category_id")
private Long categoryId;
@Column(name="title",nullable = false,unique = true)
private String title;
@Column(name="descprition",nullable = false)
private String description;
用于删除类别的代码位于**CategoryServiceImpl-**中
@Override
public void deleteCategory(String categoryId) {
Optional<Category> category=this.categoryRepository.findById(Long.parseLong(categoryId));
if(category.isPresent()){
this.categoryRepository.deleteById(Long.parseLong(categoryId));
}
else
throw new ResourceNotFoundException("Category", "category id", categoryId);
}
代码创建一个名为**enrolled-**x1c 0d1xx 1c 1d 1x的表
**问题-**尝试使用此方法删除类别时,出现以下错误-
2022-11-26 16:06:26.137 ERROR 20808 --- [nio-8086-exec-9] o.a.c.c.C.[.[.[/].
[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`assessment_portal`.`enrolled`, CONSTRAINT `FKn8uund92met1kb1iduidshdje` FOREIGN KEY (`category`) REFERENCES `category` (`category_id`))
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117) ~[mysql-connector-j-8.0.31.jar:8.0.31]
请帮助我找到正确的方法来删除类别实体,而不删除用户。
2条答案
按热度按时间dz6r00yl1#
导致此错误的原因是您要删除的类别与用户表相关联。因此,您可以将
cascade = CascadeType.REMOVE
与@ManyToMany
一起使用,也可以禁用外部检查:z5btuh9x2#
请将下面的@ManyToMany关系添加到您的类别实体。