[英]JHipster Post REST API Displays SQL Error
我正在使用JHipster创建一个项目。 我有2个实体(课程,学生),并且它们具有多对多关系。 因此,还有另一个名为Course_Student的实体,它具有2列(student_id,course_id)。 学生(用户)需要通过单击自己面板上的“注册课程”按钮来注册课程。 所以我写了一个查询和休息API函数。
这是我的查询功能:
@Modifying
@Query(value="insert into COURSE_STUDENT (STUDENTS_ID, COURSES_ID) VALUES (:studentId,:courseId)",nativeQuery = true)
@Transactional
void registerCourse(@Param("studentId") Long studentId, @Param("courseId") Long courseId);
和Rest API函数:
@PostMapping("/registercourse/{studentId}/{courseId}")
@Timed
public ResponseEntity<Void> registerCourse(@PathVariable Long studentId,@PathVariable Long courseId) {
log.debug("REST request to register {} Course : {} Student : {}", courseId,studentId);
courseRepository.registerCourse(studentId,studentId);
return ResponseEntity.ok().headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, courseId.toString())).build();
}
但是,当我尝试使用Swagger控制台运行registerCourse API时,显示以下错误:(我输入的学生ID:33,课程ID:1)
c.m.m.w.rest.errors.ExceptionTranslator : An unexpected error occurred: could not execute statement; SQL [n/a]; constraint ["FK_COURSE_STUDENT_COURSES_ID: PUBLIC.COURSE_STUDENT FOREIGN KEY(COURSES_ID) REFERENCES PUBLIC.COURSE(ID) (33)"; SQL statement:
insert into COURSE_STUDENT (STUDENTS_ID, COURSES_ID) VALUES (?,?) [23506-196]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["FK_COURSE_STUDENT_COURSES_ID: PUBLIC.COURSE_STUDENT FOREIGN KEY(COURSES_ID) REFERENCES PUBLIC.COURSE(ID) (33)"; SQL statement:
insert into COURSE_STUDENT (STUDENTS_ID, COURSES_ID) VALUES (?,?) [23506-196]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:278)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:112)
... 145 common frames omitted
Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FK_COURSE_STUDENT_COURSES_ID: PUBLIC.COURSE_STUDENT FOREIGN KEY(COURSES_ID) REFERENCES PUBLIC.COURSE(ID) (33)"; SQL statement:
insert into COURSE_STUDENT (STUDENTS_ID, COURSES_ID) VALUES (?,?) [23506-196]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
... 163 common frames omitted
2017-09-08 08:58:57.099 WARN 7528 --- [ XNIO-2 task-8] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.
您正在将student_id作为course_id传递,并且不存在ID为33的课程。请参见Rest API的registerCourse
的第三行:
courseRepository.registerCourse(studentId,studentId);
改成:
courseRepository.registerCourse(studentId,courseId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.