2 回答

TA貢獻1827條經驗 獲得超8個贊
也許您在服務方法中實現了類似的東西(您沒有顯示它),但我認為它丟失了:您沒有級聯任何東西(分別保存另一個類的對象)。您應該將@ManyToMany
注釋更改為@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
.?這會導致級聯合并和持久操作(保存新對象或任何更改都會導致自動更新另一個對象)。
更新:基于@Alan Hay 的帖子實施
模型
@Entity
public class Actor {
? ? @Id
? ? @GeneratedValue(strategy = GenerationType.IDENTITY)
? ? private Long id;
? ? private String name;
? ? private String surname;
? ? private String age;
? ? @ManyToMany
? ? @JoinTable(name = "movie_actor")
? ? private List<Movie> movies = new ArrayList<>();
? ? public void addMovie(Movie movie) {
? ? ? ? movies.add(movie);
? ? ? ? movie.getActors().add(this);
? ? }
? ? public void removeMovie(Movie movie) {
? ? ? ? movies.remove(movie);
? ? ? ? movie.getActors().remove(this);
? ? }
? ? // Constructors, getters and setters...
? ? // Equals and hashCode methods a la?
? ? // https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
}
@Entity
public class Movie {
? ? @Id
? ? @GeneratedValue(strategy = GenerationType.IDENTITY)
? ? private Long id;
? ? private String title;
? ? private String genre;
? ? private String year;
? ? @ManyToMany(mappedBy = "movies", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
? ? private List<Actor> actors;
? ? public Movie(String title, String genre, String year, List<Actor> actors) {
? ? ? ? this.title = title;
? ? ? ? this.genre = genre;
? ? ? ? this.year = year;
? ? ? ? actors.forEach(a -> a.addMovie(this));
? ? }
? ? // Getters and setters...
}
創建方法
@GetMapping("/create")
public void create() {
? ? Actor actor1 = new Actor("Pedro", "Perez", "40");
? ? Actor actor2 = new Actor("Alfredo", "Mora", "25");
? ? Actor actor3 = new Actor("Juan", "Martinez", "20");
? ? Actor actor4 = new Actor("Mario", "Arenas", "30");
? ? List<Actor> actorList = new ArrayList<>();
? ? actorList.add(actor1);
? ? actorList.add(actor2);
? ? actorList.add(actor3);
? ? actorList.add(actor4);
? ? Movie movie = new Movie("Titanic", "Drama", "1984", actorList);
? ? movieService.create(movie);
}

TA貢獻1853條經驗 獲得超18個贊
這里有兩個問題。
首先,您尚未設置關系的級聯選項。
@ManyToMany(mappedBy = "movies", cascade = {CascadeType.PERSIST, CascadeType.MERGE}) private List<Actor> actors;
其次,在雙向關系的情況下,您有責任在內存模型中維護關系的雙方。這里的關系由 Actor(沒有 的一方)管理mappedBy
,但您尚未將任何電影添加到 Actor 的電影集合中。
因此,如果您在電影構造函數中迭代演員并添加電影a.getMovies().add(this)
,那么雙方都將被設置,并且數據應根據要求保存。
Hibernate 文檔建議@ManyToMany
應避免映射,因為在大多數情況下,您可能希望存儲與關聯相關的其他數據:例如,在您的情況下,角色名稱。更靈活的選擇是創建一個連接實體,例如 MovieAppearance,它具有 Movie、Actor 和其他所需的屬性。
添加回答
舉報