更新实体 spring jpa 时出现分离实体问题

detached entity issue when updating entity spring jpa

我查看了很多类似问题的答案,但没有找到可以解决我问题的答案。我现在完全迷失了。

我正在开发 Spring Boot web 应用程序,使用 Spring Data JPA 进行持久化。当我尝试对现有实体进行更新时出现以下错误:

org.hibernate.PersistentObjectException:传递给持久化的分离实体:com.project.timefit.model.WeeklyRoutinePlan

我正在尝试使用 crudRepository 编辑实体 WeeklyRoutinePlan(get、create 和 delete 方法工作正常)。

这是我服务中的方法

@Override
@Transactional
public void editRoutinePlan(WeeklyRoutinePlan routinePlan, String username) {
    WeeklyRoutinePlan oldRoutinePlan = weeklyRoutinePlanRepository.findById(routinePlan.getId()).get();
    oldRoutinePlan.setWeekDay(routinePlan.getWeekDay());
    weeklyRoutinePlanRepository.save(oldRoutinePlan);
}

为了调试,我对其进行了简化,通常我会进行用户名验证并映射其他字段。我仍然收到这个简化版本的错误。如果我不更改工作日,我什至会得到它。

我的实体本身看起来像这样

@Entity
@Data
@SuperBuilder
@NoArgsConstructor
public class WeeklyRoutinePlan{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @ManyToOne
    private Routine routine;
    private LocalTime startTime;
    private LocalTime endTime;
    private Integer weekDay;
    @ManyToOne
    private Program program;

    public void setRoutine(Routine routine) {
        if(routine == this.routine){
            return;
        }
        if(this.routine != null){
            this.routine.getWeeklyRoutinePlans().remove(this);
        }
        if(!routine.getWeeklyRoutinePlans().contains(this)){
            routine.getWeeklyRoutinePlans().add(this);
        }
        this.routine = routine;
    }

    public void setProgram(Program program) {
        if(program == this.program){
            return;
        }
        if(this.program != null){
            this.program.getWeeklyRoutines().remove(this);
        }
        if(!program.getWeeklyRoutines().contains(this)){
            program.getWeeklyRoutines().add(this);
        }
        this.program = program;
    }
}

这是相关的实体(虽然我不确定这是否相关,因为我什至没有更新关系)

常规

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Routine {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @ManyToOne
    private User user;
    private String name;
    private Integer numberOfCycles;
    private Color color;
    @ManyToMany(mappedBy = "routines")
    private List<Exercise> exercises;
    @OneToMany(mappedBy = "routine", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<WeeklyRoutinePlan> weeklyRoutinePlans = new ArrayList<>();
    @OneToMany(mappedBy = "routine", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<FrequencyRoutinePlan> frequencyRoutinePlans = new ArrayList<>();
    @OneToMany(mappedBy = "routine", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<IndividualRoutinePlan> individualRoutinePlans = new ArrayList<>();

    public void remove(){
        exercises.forEach(exercise -> exercise.getRoutines().remove(this));
        exercises = new ArrayList();
    }
    public void setExercises(List<Exercise> exercises){
        exercises.forEach(e -> {
            if(e.getRoutines().stream().noneMatch(r -> Objects.equals(r.getId(), this.getId())))
                e.getRoutines().add(this);
        });
        this.exercises = exercises;
    }

    public void setWeeklyRoutinePlans(List<WeeklyRoutinePlan> weeklyRoutinePlans) {
        if(weeklyRoutinePlans == this.weeklyRoutinePlans){
            return;
        }
        this.weeklyRoutinePlans.forEach(r -> {if(!weeklyRoutinePlans.contains(r))r.setRoutine(null);});
        weeklyRoutinePlans.forEach(r -> {if(weeklyRoutinePlans.contains(r))r.setRoutine(this);});
        this.weeklyRoutinePlans = weeklyRoutinePlans;
    }

    public void setFrequencyRoutinePlans(List<FrequencyRoutinePlan> frequencyRoutinePlans) {
        if(frequencyRoutinePlans == this.frequencyRoutinePlans){
            return;
        }
        this.frequencyRoutinePlans.forEach(r -> {if(!frequencyRoutinePlans.contains(r))r.setRoutine(null);});
        frequencyRoutinePlans.forEach(r -> {if(frequencyRoutinePlans.contains(r))r.setRoutine(this);});
        this.frequencyRoutinePlans = frequencyRoutinePlans;
    }

    public void setIndividualRoutinePlans(List<IndividualRoutinePlan> individualRoutinePlans) {
        if(individualRoutinePlans == this.individualRoutinePlans){
            return;
        }
        this.individualRoutinePlans.forEach(r -> {if(!individualRoutinePlans.contains(r))r.setRoutine(null);});
        individualRoutinePlans.forEach(r -> {if(individualRoutinePlans.contains(r))r.setRoutine(this);});
        this.individualRoutinePlans = individualRoutinePlans;
    }

    @Override
    public String toString() {
        return "Routine{" +
                "id=" + id +
                ", user=" + user.getUsername() +
                ", name='" + name + '\'' +
                ", numberOfCycles=" + numberOfCycles +
                ", color=" + color +
                '}';
    }
}

计划

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
public class Program {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private ProgramSetting programSetting = ProgramSetting.WEEKLY;
    private Integer frequency = 1;
    @OneToMany(mappedBy = "program", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<WeeklyRoutinePlan> weeklyRoutines = new ArrayList<>();
    @OneToMany(mappedBy = "program", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<FrequencyRoutinePlan> frequencyRoutines = new ArrayList<>();
    @OneToMany(mappedBy = "program", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<IndividualRoutinePlan> individualRoutines = new ArrayList<>();
    @ManyToOne
    private User user;

    public void setWeeklyRoutines(List<WeeklyRoutinePlan> weeklyRoutines) {
        if(weeklyRoutines == this.weeklyRoutines){
            return;
        }
        this.weeklyRoutines.forEach(r -> {if(!weeklyRoutines.contains(r))r.setProgram(null);});
        weeklyRoutines.forEach(r -> {if(weeklyRoutines.contains(r))r.setProgram(this);});
        this.weeklyRoutines = weeklyRoutines;
    }

    public void setFrequencyRoutines(List<FrequencyRoutinePlan> frequencyRoutines) {
        if(frequencyRoutines == this.frequencyRoutines){
            return;
        }
        this.frequencyRoutines.forEach(r -> {if(!frequencyRoutines.contains(r))r.setProgram(null);});
        frequencyRoutines.forEach(r -> {if(frequencyRoutines.contains(r))r.setProgram(this);});
        this.frequencyRoutines = frequencyRoutines;
    }

    public void setIndividualRoutines(List<IndividualRoutinePlan> individualRoutines) {
        if(individualRoutines == this.individualRoutines){
            return;
        }
        this.individualRoutines.forEach(r -> {if(!individualRoutines.contains(r))r.setProgram(null);});
        individualRoutines.forEach(r -> {if(individualRoutines.contains(r))r.setProgram(this);});
        this.individualRoutines = individualRoutines;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public String toString() {
        return "Program{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", programSetting=" + programSetting +
                ", frequency=" + frequency +
                ", user=" + user.getUsername() +
                '}';
    }
}

此时我有点绝望,因为我的其他实体工作正常,但我只是不明白我做错了什么。该方法是事务性的,因此在我进行保存时不应分离实体。

如果我不显式调用保存,我会遇到同样的问题,因为无论如何这是由框架完成的。

我试过将关系上的获取设置为 LAZY,我也试过 EAGER,我试过只删除 Program 上的级联,尽管最佳实践是全部,但我读了一些人们对 PERSIST 有疑问。

我已经确保我的 setter 正确更新了关系,尽管正如我所说我已经简化了更新,以至于我什至没有使用它们。

我很茫然

来自评论的回答:

您将实例 WeeklyRoutinePlan (routinePlan) 传递给该方法。我猜这是分离的,因为它是在其他地方加载的。您能否尝试将 id 直接传递为 Long (routinePlan.getId())。或者尝试合并 routinePlan 并将合并的实体再次分配给 routinePlan

-> 所以问题是我从 DTO 创建的实体有一个 ID,所以它被算作一个分离的实体,即使我没有试图保存那个实体。