我正在尝试向MySQL数据库添加影片,这是我的数据库架构:
stopping
这是我的模型课:
Movie.ts
Movie(id, name)
Genre(id, name)
Movie_genre(id_movie, id_genre)
Genre.ts
public class Movie {
private Short id;
private String name;
private List<MovieGenre> movieGenres;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public Short getId() {
return id;
}
public void setId(Short id) {
this.id = id;
}
@Column(name = "name", nullable = false, length = 100)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(mappedBy = "movie")
public List<MovieGenre> getMovieGenres() {
return movieGenres;
}
public void setMovieGenres(List<MovieGenre> movieGenres) {
this.movieGenres = movieGenres;
}
}
MovieGenre.ts (该模型代表生成的表)
public class Genre {
private Short id;
private String name;
private List<MovieGenre> movieGenres;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public Short getId() {
return id;
}
public void setId(Short id) {
this.id = id;
}
@Column(name = "name", nullable = false, length = 15)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(mappedBy = "genre")
@JsonIgnore
public List<MovieGenre> getMovieGenres() {
return movieGenres;
}
public void setMovieGenres(List<MovieGenre> movieGenres) {
this.movieGenres = movieGenres;
}
}
并且由于我们在最后一个模型中有复合键,因此我们需要一个类:
public class MovieGenre {
private MovieGenrePK id;
private Movie movie;
private Genre genre;
@EmbeddedId
@JsonIgnore
public MovieGenrePK getId() {
return id;
}
public void setId(MovieGenrePK id) {
this.id = id;
}
@MapsId("movieId")
@ManyToOne
@JoinColumn(name = "movie_id", referencedColumnName = "id", nullable = false)
@JsonIgnore
public Movie getMovie() {
return movie;
}
public void setMovie(Movie movie) {
this.movie = movie;
}
@MapsId("genreId")
@ManyToOne
@JoinColumn(name = "genre_id", referencedColumnName = "id", nullable = false)
public Genre getGenre() {
return genre;
}
public void setGenre(Genre genre) {
this.genre = genre;
}
}
因此,我尝试通过发布请求来添加带有流派的电影,首先我发布了一个请求以添加电影,另一个发布了一个请求以添加流派,这很好,现在我需要将一个流派关联到电影。
我尝试了以下方法:
我向以下端点发出了POST请求:public class MovieGenrePK implements Serializable {
private Short movieId;
private Short genreId;
@Column(name = "movie_id", nullable = false)
public Short getMovieId() {
return movieId;
}
public void setMovieId(Short movieId) {
this.movieId = movieId;
}
@Column(name = "genre_id", nullable = false)
public Short getGenreId() {
return genreId;
}
public void setGenreId(Short genreId) {
this.genreId = genreId;
}
}
,具有application / json标头和以下正文:
http://localhost:8080/api/movieGenres
但是我得到了错误:
{
"movie": "http://localhost:8080/api/movies/6",
"genre": "http://localhost:8080/api/genres/1"
}
答案 0 :(得分:2)
您必须使MovieGenrePK无效,更改:
public class MovieGenre {
private MovieGenrePK id;
}
到
public class MovieGenre {
private MovieGenrePK id = new MovieGenrePK();
}