最近写jpa 的单项多对多,出现的错误,记录一下
java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`dj_examination_service`.`dj_exam_bank_rules`, CONSTRAINT `dj_exam_bank_rules_ibfk_1` FOREIGN KEY (`question_bank_id`) REFERENCES `dj_exam_question_bank` (`id`))
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:975)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1114)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1062)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1383)
找了半天 网上的帖子是说对应的主键不存在,但是我的数据库中明明是早已就创建好的。
这时候查看sql输出内容发现端倪。insert 的值 反了,最终找到配置多对多关系的时候 对应的id写反了
实体SelectionRules 中错误的配置
@ManyToMany
@JoinTable(name="dj_exam_bank_rules",joinColumns={@JoinColumn(name="question_bank_id",referencedColumnName ="id")},
inverseJoinColumns ={@JoinColumn(name="rules_id",referencedColumnName ="id")} )
private Set<QuestionBank> bankSet = new HashSet<>();
正确配置 如下
@ManyToMany
@JoinTable(name="dj_exam_bank_rules",joinColumns={@JoinColumn(name="rules_id",referencedColumnName ="id")},
inverseJoinColumns ={@JoinColumn(name="question_bank_id",referencedColumnName ="id")} )
private Set<QuestionBank> bankSet = new HashSet<>();