【问题标题】:Hibernate ManyToMany deleted object would be re-saved by cascadeHibernate ManyToMany删除的对象将被级联重新保存
【发布时间】:2014-03-31 21:11:30
【问题描述】:

由于某种原因,我无法删除属于多对多关系的对象。我收到以下错误:

Exception in thread "main" org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations): [edu.cs157b.hibernate.AppointmentRequest#11]
    at org.hibernate.internal.SessionImpl.forceFlush(SessionImpl.java:1232)

这是我映射多对多关系的三个类。从本质上讲,Doctor 有很多 Patients 到 AppointmentRequest,反之亦然。这是课程

医生

package edu.cs157b.hibernate;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.*;

@Entity
@Table(name="DOCTOR_INFO")
@NamedQueries (
    {
        @NamedQuery(name = "Doctor.getAll", query = "from Doctor"),
        @NamedQuery(name = "Doctor.findByName", query = "from Doctor where name = :name")
    }
)
public class Doctor implements Person {

    private int id;
    private String name;
    private Specialty specialty;
    private List<AppointmentRequest> appointmentRequests = new ArrayList<AppointmentRequest>();

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Column(unique=true)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @ManyToOne (fetch = FetchType.EAGER, cascade= CascadeType.PERSIST) 
    @JoinColumn(name="specialty_id") 
    public Specialty getSpecialty() {
        return specialty;
    }

    public void setSpecialty(Specialty specialty) {
        this.specialty = specialty;
    }

    @OneToMany(mappedBy="doctor", targetEntity = AppointmentRequest.class, 
             fetch=FetchType.EAGER, orphanRemoval=true, cascade= CascadeType.ALL) 
    public List<AppointmentRequest> getAppointmentRequests() {
        return this.appointmentRequests;
    }

    public void setAppointmentRequests(List<AppointmentRequest> appointmentRequests) {
        this.appointmentRequests = appointmentRequests;
    }

    @Transient
    public List<Patient> getPatients() {
        List<Patient> patients = new ArrayList<Patient>();

        for(AppointmentRequest appointment:appointmentRequests) {
            patients.add(appointment.getPatient());
        }
        return patients;
    }
}

患者

package edu.cs157b.hibernate;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.*;

@Entity
@Table(name="PATIENT_INFO")
@NamedQueries (
    {
        @NamedQuery(name = "Patient.getAll", query = "from Patient"),
        @NamedQuery(name = "Patient.findByName", query = "from Patient where name = :name")
    }
)
public class Patient implements Person {

    private int id;
    private String name;
    private String medical_record;
    private List<AppointmentRequest> appointmentRequests = new ArrayList<AppointmentRequest>();

    public String getMedical_record() {
        return medical_record;
    }

    public void setMedical_record(String medical_record) {
        this.medical_record = medical_record;
    }

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Column(unique=true)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(mappedBy="patient", targetEntity = AppointmentRequest.class, 
             fetch=FetchType.EAGER, orphanRemoval=true, cascade= CascadeType.ALL) 
    public List<AppointmentRequest> getAppointmentRequests() {
        return this.appointmentRequests;
    }

    public void setAppointmentRequests(List<AppointmentRequest> appointmentRequests) {
        this.appointmentRequests = appointmentRequests;
    }

    @Transient
    public List<Doctor> getDoctors() {
        List<Doctor> doctors = new ArrayList<Doctor>();

        for(AppointmentRequest appointment:appointmentRequests) {
            doctors.add(appointment.getDoctor());
        }
        return doctors;
    }
}

ApppointmentRequest

package edu.cs157b.hibernate;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TimeZone;

import javax.persistence.*;

import org.hibernate.annotations.Type;

import java.util.List;

@Entity
@Table(name="APPOINTMENT_REQUEST")
@NamedQueries (
    {
        @NamedQuery(name = "AppointmentRequest.getAll", query = "from AppointmentRequest"),
        @NamedQuery(name = "AppointmentRequest.findByDoctorId", query = "from AppointmentRequest where doctor_id = :doctor_id"),
        @NamedQuery(name = "AppointmentRequest.findByPatientId", query = "from AppointmentRequest where patient_id = :patient_id"),
        @NamedQuery(name = "AppointmentRequest.findByID", query = "from AppointmentRequest where id = :id")
    }
)
public class AppointmentRequest {

    private int id;

    private Doctor doctor;
    private Patient patient;
    private boolean fulfilled = false;
    private Calendar time;
    private final SimpleDateFormat timestampFormat = new SimpleDateFormat("MM/dd/yyyy h a");


    public Calendar getTime() {
        return time;
    }

    @Transient
    public String getFormattedTime() {  
        String result = timestampFormat.format(time.getTime());
        return result;
    }

    public void setTime(Calendar time) {
        this.time = time;
    }
    public boolean isFulfilled() {
        return fulfilled;
    }
    public void setFulfilled(boolean fulfilled) {
        this.fulfilled = fulfilled;
    }
    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    @ManyToOne (fetch = FetchType.EAGER, cascade= CascadeType.PERSIST) 
    @JoinColumn(name="doctor_id") 
    public Doctor getDoctor() {
        return doctor;
    }

    public void setDoctor(Doctor doctor) {
        this.doctor = doctor;
    }

    @ManyToOne (fetch = FetchType.EAGER, cascade= CascadeType.PERSIST) 
    @JoinColumn(name="patient_id") 
    public Patient getPatient() {
        return patient;
    }

    public void setPatient(Patient patient) {
        this.patient = patient;
    }    

}

医生删除方法

public void deleteDoctor(String doctor_name) {
    Session session = sessionFactory.openSession();
    Doctor doctor = new Doctor();
    try {
        session.beginTransaction();
        Query query = session.getNamedQuery("Doctor.findByName");
        query.setString("name", doctor_name);
        doctor = (Doctor) query.uniqueResult();
        if(doctor == null) {
            throw new NullPointerException();
        }
        List<AppointmentRequest> appointments = doctor.getAppointmentRequests();
        for(AppointmentRequest appointment:appointments) {
            appointment.setDoctor(null);
        }
        session.delete(doctor);
        session.getTransaction().commit();
    }
    finally {
        session.close();
    }
}

【问题讨论】:

    标签: java eclipse hibernate jpa


    【解决方案1】:

    这个异常的真正含义是你告诉 Hibernate 从数据库中删除对象,但同时这个对象仍然存在(这意味着仍然存在于 java 或数据库中)通过带有 CascadeType.PERSIST 注释的持久实体映射集合中它。

    这就像用弹性橡胶把东西绑在窗户上,然后戳它,希望它会掉下来。 Hibernate 很聪明,它可以让你免于做无意义的事情,它会告诉你该做什么

    删除的对象将被重新保存 通过级联(从关联中删除已删除的对象)

    您正在执行appointment.setDoctor(null);,它将从集合中删除对象(仅在java中,因为您没有显式或隐式更新appointment)。您在@上有CascadeType.PERSIST 987654327@ 这意味着当休眠将提交事务时,它会发现 appointment 与您刚刚删除的 doctor 有关联,这意味着如果您从表中删除那个 doctor,hibernate 必须去创建相同的 doctor 因为你没有告诉他在 appointment 因为他遵循您设置的所有实体规则。由于hibernate很聪明,他知道这一点,他会为你抛出一个异常,说不要自相矛盾,做正确的事。

    现在我能想到的解决方案不止一种

    1. 在AppointmentRequest 中的getDoctor() 上使用cascade={CascadeType.PERSIST,CascadeType.REMOVE} 或cascade=CascadeType.ALL

    2. 如休眠文档here中所述

      在@ManyToOne 或 @ManyToMany 关联。 Cascade 通常对 @OneToOne 和 @OneToMany 关联。

      从getDoctor移除级联

    3. 由于您在getDoctor() 上指定了FetchType.EAGER 并指定了cascade,因此解释休眠的行为对我来说有点复杂,但在this 问题中,他们已经通过使用FetchType.LAZY 解决了我不确定是否它会为你解决的。

    4. 你可以在所有有这个医生的AppointmentRequest上做session.saveOrUpdate(appointment),然后去session.delete(doctor);

    希望这能解决您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多