hibernate - Spring JPA 一对多休眠插入数据与现有实体
问题描述
我正在尝试将实体插入数据库,但该实体具有一对多关系,并且其中一个实体已经存在于数据库中。例如,让我们想想Course和Instructor,当您使用现有 Instructor 创建 Course 时,我有Status 500 error。
我的代码如下:
- 我正在使用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
,你需要参考现有的
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);
}
推荐阅读
- redirect - Identity Server 4 - 取消重定向到登录并返回 401
- node.js - shopify结账支付api上的404
- domain-driven-design - DDD - 执行需要了解多个聚合根的规则
- jquery - 检查输入值是否与 ids 值相同
- node.js - 将限制设置为最大行数
- date - 根据当前周的天数获取 Teradata 中的最后/当前星期二日期
- python - Python MysqlClient(MYSQLDB)无法连接到远程服务器
- r - 根据 POSIxct 值创建新变量 <
- php - 无法通过 PHPExcel 从 Excel 获取公式结果
- javascript - 功能作为反应孩子无效,为什么我会得到这个?