repository.save()不会持久化cascadetype=all的实体

lndjwyie  于 2021-07-26  发布在  Java
关注(0)|答案(0)|浏览(185)

我想向数据库中的实体添加级联。我补充道 @OneToMany(mappedBy = "exercise",cascade = CascadeType.ALL, fetch = FetchType.EAGER) 以测试其工作方式。但是,在保存父实体时,子实体似乎根本没有保存。在网上搜索答案时,我发现session显然有保存和/或持久化实体的方法。问题是,我对会话的工作方式感到非常困惑,没有任何尝试成功。我的问题是,级联与 repository.save() ? 如果没有,最好的方法是什么?提前谢谢。
父实体:

@Getter
@Setter
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Module {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Builder.Default
    @OneToMany(mappedBy = "module", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    @Fetch(value = FetchMode.SUBSELECT)
    @JsonBackReference
    private List<Exercise> exercises = new ArrayList<>();

    public void saveExercise(Exercise exercise) {
        int index = exercises.indexOf(exercise);
        if (index == -1) {
            exercises.add(exercise);
        } else {
            exercises.set(index, exercise);
        }
    }
    // methods
}

子实体

@Getter
@Setter
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Exercise {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NonNull
    @ManyToOne
    @JsonManagedReference
    private Module module;

    // methods
}

模块服务

@Transactional
@Service
public class ModuleService {

public void saveModule(Module module) {
        moduleRepository.save(module);
    }
}

健身服务:

@Transactional
@Service
public class ExerciseService {
    public void saveExercise(Exercise exercise) {
        // Get parent in relationship
        Module module = exercise.getModule();

        // Update parent
        module.saveExercise(exercise);

        // Save parent
        moduleService.saveModule(module);
    }
    public Exercise getExerciseById(Long exerciseId) {
        return exerciseRepository.findById(exerciseId).orElseThrow();
    }

}

测试:

@Test
    public void testSaveDeleteExercise() {
        Exercise exercise = Exercise.builder().id(101L).module(module).build();

        exerciseService.saveExercise(exercise);

        assertThat(exerciseService.getExerciseById(exercise.getId())).isEqualTo(exercise);
}

除此之外:

java.util.NoSuchElementException: No value present

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题