我想在entites Movie和Genre之间创建一个ManyToMany关系。因为电影可以有很多类型,而且类型可以有很多电影。但我不知道怎么做这个联想。我必须创建实体“genre_movie”?如果我编译它,则生成更多表:movie_genre和genre_movie。我只想要一个。
@Entity
public class Movie implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@JsonView(Views.Private.class)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonView(Views.Private.class)
private String name;
@JsonView(Views.Private.class)
private Long year;
@JsonView(Views.Private.class)
private String sinopsis;
@JsonView(Views.Private.class)
private Double puntuation;
@JsonView(Views.Private.class)
private Long duration;
@JsonView(Views.Private.class)
private String idioma;
@JsonView(Views.Private.class)
private String trailer;
//getters seters
@ManyToMany(targetEntity=Genre.class)
private Set teacherSet;
}
类型课
import com.fasterxml.jackson.annotation.JsonView;
import javax.persistence.*;
import java.io.Serializable;
import java.util.*;
@Entity
public class Genre implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@JsonView(Views.Private.class)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonView(Views.Private.class)
private String genreName;
public Genre(){}
public Genre(String genreName){
this.genreName = genreName;
}
@ManyToMany(targetEntity = Movie.class)
private Set movieSet;
public String getName() {
return genreName;
}
public void setName(String name) {
this.genreName = name;
}
}
查询:
insert into Movie (name,year,sinopsis,puntuation,duration,idioma,trailer) values ('Titanic',1997,'Is about a movie ....',0,88,'english','https://www.youtube.com/watch?v=zCy5WQ9S4c0&t=112s');
insert into Movie (name,year,sinopsis,puntuation,duration,idioma,trailer) values ('Nightcrawler',2014,'Is about a movie dpsvr....',0,175,'english','https://www.youtube.com/watch?v=u1uP_8VJkDQ');
insert into Movie (name,year,sinopsis,,,idioma,trailer) values ('Iron Man 2',2010,'Is about a movie dpsvr....',0,145,'english','https://www.youtube.com/watch?v=BoohRoVA9WQ');
insert into Genre (genreName) values ('comedy');
insert into Genre (genreName) values ('drama');
insert into Genre (genreName) values ('thriller');
insert into Genre (genreName) values ('terror');
答案 0 :(得分:0)
@Entity
public class Movie implements Serializable {
@ManyToMany
private Set<Genre> teacherSet;
}
@Entity
public class Genre implements Serializable {
@ManyToMany(mappedBy="teacherSet")
private Set<Movie> movieSet;
}
在此示例中,将仅生成Movie和Genre之间的一个关系,其中关系的所有者将是Movie。在SQL中,将生成一个关联表Movie_Genre。