JPA - 级联类型全部不起作用

JPA - does not work cascada type all

我在数据库中保存实体列表时遇到问题。

我有实体

@Entity
@Table(name = "movies")
@Data
public class MovieEntity {

    @Id
    @Column(unique = true, updatable = false)
    @GeneratedValue
    private Long id;

    @OneToMany(mappedBy = "movie", cascade = CascadeType.ALL)
    private Set<MovieDescription> descriptions;
}

和类

@Entity
@Data
@EqualsAndHashCode(callSuper = true)
@DiscriminatorValue(value = MovieField.Values.DESCRIPTION)
public class MovieDescription extends MovieInfo {

    private String description;
}

继承自

@Entity
@Table(name = "movies_info")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "dtype")
@Data
public class MovieInfo {

    @Id
    @Column(unique = true, updatable = false)
    @GeneratedValue
    private Long id;

    @ManyToOne
    private MovieEntity movie;
}

虽然我在使用这样的代码时cascade = CascadeType.ALL

final MovieEntity movie = new MovieEntity();
    movie.setStatus(EditStatus.WAITING);
    movie.setTitle(movieDTO.getTitle());
    movie.setType(movieDTO.getType());
    movieDTO.getDescription().ifPresent(description -> {
        MovieDescription movieDescription = new MovieDescription();
        movieDescription.setDescription(description);
        movie.getDescriptions().add(movieDescription);
    });
this.movieRepository.save(movie);

将对象本身MovieEntity保存到数据库而不MovieDescription。映射列表不会保存到数据库中。为什么?

在你的例子中 MovieDescription class 是关系所有者。

暗示了这一点
@OneToMany(*mappedBy = "movie"*, cascade = CascadeType.ALL)
private Set<MovieDescription> descriptions;

JPA 仅与所有者保持关系,但您没有在描述中设置 MovieEntity link

    MovieDescription movieDescription = new MovieDescription();
    movieDescription.setDescription(description);
    movie.getDescriptions().add(movieDescription);

添加下一行使其工作:

    movieDescription.setMovie(movie);