映射列表不会与实体一起保存到数据库中

时间:2017-10-07 22:58:57

标签: java spring hibernate spring-mvc spring-boot

未保存映射列表。我为MovieDescription实体设置了值,然后将该实体添加到MovieEntity实体列表中并将其保存到数据库中。但是,MovieDescription实体不会保存。

我有主要实体

@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;
}

然后我有一个实体

@MappedSuperclass
@Data
public class MovieInfo {

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

    @ManyToOne
    private MovieEntity movie;

    @ManyToOne
    private UserEntity user;

    private EditStatus status;

    private Integer points;
}

然后我有描述实体

@Entity
@Data
@EqualsAndHashCode(callSuper = true)
public class MovieDescription extends MovieInfo {

    private String description;
}

然后我尝试将电影保存到基地

@Override
public void createMovie(
        @NotNull @Valid final MovieDTO movieDTO,
        @Min(1) final Long userId
) throws ResourceNotFoundException {
    final UserEntity user = this.userRepository.findByIdAndEnabledTrue(userId).get();

    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);
        movieDescription.setUser(user);
        movieDescription.setStatus(EditStatus.WAITING);
        movie.getDescriptions().add(movieDescription);
        System.out.println(movieDescription);
    });
    this.movieRepository.save(movie)

2 个答案:

答案 0 :(得分:0)

您只需要:

movieDescription.setMovie(movie)

答案 1 :(得分:0)

因此,最好的方法是在MovieEntity类中使用一个方便的方法,这将使您的代码看起来干净,并且您不会忘记将引用设置为双向方式。

@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;

    public void addMovieDescription(MovieDescription movieDescription){
         movieDescription.setMovie(this);
         descriptions.add(movieDescription);
    }
}