我有一個OneToMany關系(兩個表雙向)。當我保存醫生的專業時,它確實有效,但是當我洗掉任何專業并更新醫生時,它不起作用。
醫生
@Entity
@Table(name = "doctors")
public class Doctor implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer doctorId;
@Column(length = 20)
private String doctorName;
@Column(length = 9)
private String doctorPhoneNo;
@Column(length = 30)
private String doctorEmailAddress;
private String doctorProfileImage;
@Enumerated(EnumType.STRING)
private Status status;
@Column(length = 6)
private String doctorCmp;
@OneToMany(mappedBy = "doctor", cascade = CascadeType.ALL)
// @JsonIgnore
private Set<DoctorSpecialties> doctorSpecialties;
public Doctor() {
this.doctorSpecialties = new HashSet<>();
}
public Doctor(Integer id){
this();
this.doctorId = id;
}
// getters y setters
}
專業
@Entity
@Table(name = "specialties")
public class Specialty implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer specialtyId;
private String specialtyName;
@OneToMany(mappedBy = "specialty")
@JsonIgnore
private Set<DoctorSpecialties> doctorSpecialties;
public Specialty() {
}
public Specialty(Integer id) {
this.specialtyId = id;
}
// getters and setters
}
醫生專長
@Entity
@Table(name = "doctor_specialties")
public class DoctorSpecialties implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "doctor_id")
private Doctor doctor;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "specialty_id")
private Specialty specialty;
@OneToMany
@JoinColumn(name = "doctor_specialties_id")
private Set<Appointment> appointments;
@OneToMany
@JoinColumn(name = "doctor_specialties_id")
private Set<DoctorSchedule> schedules;
public DoctorSpecialties(){
}
public DoctorSpecialties(Specialty specialty, Doctor doctor){
this.specialty = specialty;
this.doctor = doctor;
}
getters / setters
}
控制器
@PostMapping(value = "/saveSpecialties/{id}")
public String saveDoctorSpecialties(@RequestParam(required = false) String[] specialtiesId,
@PathVariable Integer id, RedirectAttributes message) {
if (id != null && id > 0) {
Doctor doctor = doctorService.findOne(id);
if (doctor != null) {
// It does not work
doctor.getDoctorSpecialties().forEach(ds -> doctorSpecialtiesService.delete(ds.getId()));
doctor.getDoctorSpecialties().clear();
if (specialtiesId != null) {
for (String specialtyId : specialtiesId) {
DoctorSpecialties ds = new DoctorSpecialties();
ds.setSpecialty(new Specialty(Integer.parseInt(specialtyId)));
ds.setDoctor(doctor);
doctor.getDoctorSpecialties()
.add(ds);
}
}
doctorService.update(doctor);
message.addFlashAttribute("success", "Specialties successfully saved.");
return "redirect:/doctors/profile/{id}/specialties";
}
}
// specialtiesId = new String[]{};
message.addFlashAttribute("error", "Doctor doesn't exists");
return "redirect:/doctors/list";
}
安慰:
2021-10-30 21:19:13.330 DEBUG 44504 --- [nio-8080-exec-7] org.hibernate.SQL : select doctor0_.doctor_id as doctor_i1_3_0_, doctor0_.doctor_cmp as doctor_c2_3_0_, doctor0_.doctor_email_address as doctor_e3_3_0_, doctor0_.doctor_name as doctor_n4_3_0_, doctor0_.doctor_phone_no as doctor_p5_3_0_, doctor0_.doctor_profile_image as doctor_p6_3_0_, doctor0_.status as status7_3_0_ from doctors doctor0_ where doctor0_.doctor_id=? 2021-10-30 21:19:13.339 DEBUG 44504 --- [nio-8080-exec-7] org.hibernate.SQL : select doctorspec0_.doctor_id as doctor_i2_2_0_, doctorspec0_.id as id1_2_0_, doctorspec0_.id as id1_2_1_, doctorspec0_.doctor_id as doctor_i2_2_1_, doctorspec0_.specialty_id as specialt3_2_1_ from doctor_specialties doctorspec0_ where doctorspec0_.doctor_id=? 2021-10-30 21:19:13.401 DEBUG 44504 --- [nio-8080-exec-8] org.hibernate.SQL : select doctor0_.doctor_id as doctor_i1_3_0_, doctor0_.doctor_cmp as doctor_c2_3_0_, doctor0_.doctor_email_address as doctor_e3_3_0_, doctor0_.doctor_name as doctor_n4_3_0_, doctor0_.doctor_phone_no as doctor_p5_3_0_, doctor0_.doctor_profile_image as doctor_p6_3_0_, doctor0_.status as status7_3_0_ from doctors doctor0_ where doctor0_.doctor_id=? 2021-10-30 21:19:13.404 DEBUG 44504 --- [nio-8080-exec-8] org.hibernate.SQL : select specialty0_.specialty_id as specialt1_7_0_, doctorspec1_.id as id1_2_1_, doctor2_.doctor_id as doctor_i1_3_2_, specialty0_.specialty_name as specialt2_7_0_, doctorspec1_.doctor_id as doctor_i2_2_1_, doctorspec1_.specialty_id as specialt3_2_1_, doctorspec1_.specialty_id as specialt3_2_0__, doctorspec1_.id as id1_2_0__, doctor2_.doctor_cmp as doctor_c2_3_2_, doctor2_.doctor_email_address as doctor_e3_3_2_, doctor2_.doctor_name as doctor_n4_3_2_, doctor2_.doctor_phone_no as doctor_p5_3_2_, doctor2_.doctor_profile_image as doctor_p6_3_2_, doctor2_.status as status7_3_2_ from specialties specialty0_ inner join doctor_specialties doctorspec1_ on specialty0_.specialty_id=doctorspec1_.specialty_id inner join doctors doctor2_ on doctorspec1_.doctor_id=doctor2_.doctor_id where doctor2_.doctor_id=? 2021-10-30 21:19:13.565 DEBUG 44504 --- [nio-8080-exec-4] org.hibernate.SQL : select specialty0_.specialty_id as specialt1_7_0_, doctorspec1_.id as id1_2_1_, doctor2_.doctor_id as doctor_i1_3_2_, specialty0_.specialty_name as specialt2_7_0_, doctorspec1_.doctor_id as doctor_i2_2_1_, doctorspec1_.specialty_id as specialt3_2_1_, doctorspec1_.specialty_id as specialt3_2_0__, doctorspec1_.id as id1_2_0__, doctor2_.doctor_cmp as doctor_c2_3_2_, doctor2_.doctor_email_address as doctor_e3_3_2_, doctor2_.doctor_name as doctor_n4_3_2_, doctor2_.doctor_phone_no as doctor_p5_3_2_, doctor2_.doctor_profile_image as doctor_p6_3_2_, doctor2_.status as status7_3_2_ from specialties specialty0_ inner join doctor_specialties doctorspec1_ on specialty0_.specialty_id=doctorspec1_.specialty_id inner join doctors doctor2_ on doctorspec1_.doctor_id=doctor2_.doctor_id where doctor2_.doctor_id=?
There is no delete statement...
------------------------ EDIT 1 ------------------------
Doctor find = doctorRepository.findById(1).get();
DoctorSpecialties ds1 = new DoctorSpecialties();
ds1.setSpecialty(specialtyRepository.findById(1).get());
ds1.setDoctor(find);
DoctorSpecialties ds2 = new DoctorSpecialties();
ds2.setSpecialty(specialtyRepository.findById(2).get());
ds2.setDoctor(find);
find.getDoctorSpecialties().add(ds1);
find.getDoctorSpecialties().add(ds2);
doctorRepository.save(find);
I have done some tests and I can not understand completely. I did and it only saves once when actually I am adding two objects.
insert into doctor_specialties (id, doctor_id, specialty_id) values (null, ?, ?)
------------------------ EDIT 2 ------------------------
DoctorSpecialties (Modify the constructor)
@Entity
@Table(name = "doctor_specialties")
public class DoctorSpecialties implements Serializable {
public DoctorSpecialties(Integer specialtyId, Doctor doctor) {
this.specialty = new Specialty(specialtyId);
this.doctor = doctor;
}
}
Controller
@PostMapping(value = "/saveSpecialties/{id}")
public String saveDoctorSpecialties(@RequestParam(required = false) String[] specialtiesId,
@PathVariable Integer id, RedirectAttributes message) {
if (id != null && id > 0) {
doctorService.saveDelete(id);
Doctor doctor = doctorService.findOne(id);
if (specialtiesId != null && specialtiesId.length > 0) {
for(String idSpecialty : specialtiesId){
doctorSpecialtiesService.save(new DoctorSpecialties(Integer.parseInt(idSpecialty), doctor));
}
}
message.addFlashAttribute("success", "Specialties successfully saved.");
return "redirect:/doctors/profile/{id}/specialties";
}
message.addFlashAttribute("error", "Doctor doesn't exists");
return "redirect:/doctors/list";
}
Service
@Override
@Transactional
public void saveDelete(Integer doctorId) {
Doctor doctor = this.doctorRepository
.findById(doctorId).get();
doctor.getDoctorSpecialties().clear();
}
Console:
選擇doctor0_.doctor_id如doctor_i1_3_0_,從醫生doctor0_ doctor0_.doctor_cmp如doctor_c2_3_0_,doctor0_.doctor_email_address如doctor_e3_3_0_,doctor0_.doctor_name如doctor_n4_3_0_,doctor0_.doctor_phone_no如doctor_p5_3_0_,doctor0_.doctor_profile_image如doctor_p6_3_0_,doctor0_.status如status7_3_0_其中doctor0_.doctor_id = ? 選擇doctorspec0_.doctor_id作為doctor_i2_2_0_,doctorspec0_.id作為id1_2_0_,doctorspec0_.id作為id1_2_1_,doctorspec0_.doctor_id作為doctor_i2_2_1_,doctorspec0_.specialty_id作為specialt3_2_1_來自doctor_specialties_doctorspec_doctor_spec0
更新預約 set doctor_specialties_id=null where doctor_specialties_id=?
更新doctor_schedules 設定doctor_specialties_id=null 哪里doctor_specialties_id=?
從doctor_specialties 中洗掉id=?
uj5u.com熱心網友回復:
有的一方mappedBy就是擁有的一方。
這意味著類似于:“關系這一側的修改已經映射到關系的另一側,因此無需在額外的表中單獨跟蹤它。”
檢查此 url 以獲取更多資訊ORM 映射中的“擁有方”是什么?
uj5u.com熱心網友回復:
對于事務中的一對多關系,一旦你得到了父(Doctor)并回圈了它的子(DoctorSpecialties)[換句話說,一旦你將整個父和它的子加載到 Persistent 狀態],你將無法DoctorSpecialties直接通過它洗掉你的repository。
您可以嘗試類似下面的示例來查看它:
@Transactional
public void removeLine(Long doctorId, Long specId) {
Doctor doctor = this.doctorRepository // (1)
.findById(doctorId)
.orElseThrow(IllegalArgumentException::new);
this.doctorSpecialtiesRepository.deleteById(specId); // (2)
}
在 (1) 處,我們加載doctor到持久狀態。所以在這里,如果fetch = FetchType.EAGER,這意味著它將加載doctor并全部doctorSpecialties進入持久狀態,并且這個原因(2)不會給你任何影響。
否則,如果fetch = FetchType.LAZY,則僅加載doctor到持久狀態,并且在(2)處將成功洗掉。
您的情況類似,fetch = FetchType.LAZY但您通過 using 回圈了孩子,forEach并加載doctorSpecialties到持久狀態。這就是您無法洗掉它們的原因。
建議:orphanRemoval = true在您的父物體中使用
@OneToMany(mappedBy = "doctor", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<DoctorSpecialties> dss;
只需在您的方法中清除其子項(在@Transactional 方法中)
doctor.getDoctorSpecialties().clear();
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344082.html
