我创建了Rest Api,它将学生数据保存到数据库。 而且学生编号不会成为主键,我不希望它是自动生成的, 这就是为什么我没有给出任何生成策略的原因。
学生可以有很多笔,所以有One To Many Mapping
。
每当我尝试将数据保存到db时,都会出现错误 A different object with the same identifier value was already associated with the session.
。
我知道每个主键在会话中只能有一个对象
DAO LAYER
@Autowired
private EntityManager entityManager;
public void saveStudent(Students student) {
// here i am saving data
entityManager.persist(student);
}
Pojo学生:
@Entity
@Data
@AllArgsConstructor
@Table(name = "list_of_students")
@NoArgsConstructor
public class Students implements Serializable {
private static final long serialVersionUID = -163504605143278308L;
@Column(name = "student_name")
private String name;
@Id
@Column(name = "student_roll_no")
private Long rollNo;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "student", cascade = {CascadeType.ALL})
private Set<Pen> pens = new HashSet<Pen>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "student_courses", joinColumns = { @JoinColumn(name = "student_roll_no") }, inverseJoinColumns = {
@JoinColumn(name = "course_id") })
private Set<Courses> listOfCourses = new HashSet<Courses>();
}
Pen Pojo:
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Data
@Table(name = "pens")
public class Pen {
@Id
@Column(name = "pen_color",unique=true,columnDefinition="VARCHAR(64)")
private String color;
@ManyToOne(fetch = FetchType.EAGER,cascade =CascadeType.ALL)
@JoinColumn(name="student_roll_no")
private Students student;
}
我尝试执行以下提到的操作:通过这样做,我没有收到任何错误,
但没有数据保存到pens Table
在“笔”表中,我希望学生卷不映射到笔的颜色。
@OneToMany(fetch = FetchType.EAGER, mappedBy = "student", cascade = {CascadeType.MERGE})
private Set<Pen> pens = new HashSet<Pen>();
REST CONTROLLER
@ApiOperation(value = "Add Student")
@RequestMapping(value = "add/Student", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public void addStudentData(@Valid @RequestBody Students student) {
service.save(student);
}
邮递员请求
URL:http://localhost:8080/add/Student
{
"name": "Ashish Upadhyay",
"rollNo": "1",
"pens": [{
"color": "RED",
"student":{
"rollNo":"1"
}
}],
"listOfCourses": [{
"courseName": "Data Structures",
"courseId": 1
},
{
"courseName": "Alogrithms",
"courseId": 2
},
{
"courseName": "Pysical Education",
"courseId": 3
}
]
}