首页 > 解决方案 > Spring JPA 一对多休眠插入数据与现有实体

问题描述

我正在尝试将实体插入数据库,但该实体具有一对多关系,并且其中一个实体已经存在于数据库中。例如,让我们想想CourseInstructor,当您使用现有 Instructor 创建 Course 时,我有Status 500 error

我的代码如下:

课程

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",

标签: hibernatespring-bootjpa

解决方案


而不是创建一个新的Instructor,你需要参考现有的

public Course createCourse(CourseDataSource coursetDataSource) {
    Instructor instructor = entityManager.createQuery("FROM Instructor i where i.instructor_name = :name", Instructor.class).setParameter("name", coursetDataSource.getInstructorName()).getSingleResult();

    Course course = new Course();
    course.setCourseName(coursetDataSource.getCourseName());
    course.setInstructor(instructor);
    return courseRepository.save(course);
}

推荐阅读