【发布时间】:2020-05-11 16:15:18
【问题描述】:
我正在尝试将实体插入数据库,但该实体具有一对多关系,并且其中一个实体已经存在于数据库中。例如,让我们想想 Course 和 Instructor,当您使用现有 Instructor 创建课程时,我遇到 Status 500 错误。
我的代码如下:
- 我使用的是Project Lombok 注释,所以不是使用收缩、getter 和 setter 来减少样板代码。
课程
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Entity
@Table(name = "course")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String course_name;
@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH} )
@JoinColumn(name = "instructor_fk", nullable = false)
private Instructor instructor;
}
导师
@Entity
@Table(name = "instructor")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Instructor {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(unique = true)
private String instructor_name;
@OneToMany(
mappedBy = "instructor",
cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}
)
@JsonIgnore
private List<Course> courses;
}
CRUD 存储库
@Repository
public interface CourseRepository extends CrudRepository<Course, Integer> {
}
数据源
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CourseDataSource {
private @NotEmpty
@JsonProperty("course_name")
String courseName;
private @NotEmpty
@JsonProperty("instructor_name")
String instructorName;
}
服务
@Service
public class CompartmentService {
@Autowired
private CouseRepository courseRepository;
public Course createCourse(CourseDataSource coursetDataSource) {
Instructor instructor = new Instructor();
instructor.setinstructorName(coursetDataSource.getInstructorName());
Course course = new Course();
course.setCourseName(coursetDataSource.getCourseName());
course.setInstructor(instructor);
return courseRepository.save(course);
}
但是当我与现有的 Instructor 发出 Post 请求时,我收到此错误:
"status": 500,
"error": "Internal Server Error",
"message": "could not execute statement; SQL [n/a]; constraint [instructor_pkey]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
【问题讨论】:
-
在哪里将
instructor设置为course?此行是否正确course.setRateCalculations(instructor);并且请同时发布course课程。还是Author类 -
对不起作者应该是Course,course.setRateCalculations(instructor);应该是course.setInstructor (讲师);
标签: hibernate spring-boot jpa