我有一个用户和一个电影模型。在我的应用程序中,用户可以将电影对象保存到数据库中。我想在用户和他们添加的电影之间建立关系。
我从Angular前端获得了一个电影对象:
@RequestMapping(value = "/", method = RequestMethod.POST)
public Movie createMovie(@RequestBody Movie movie){
return movieService.createMovie(movie);
}
这将调用服务和createMovie函数:
@Override
public Movie createMovie(Movie movie) {
return movieRepository.save(movie);
}
现在,影片对象已添加到数据库中的影片表中,但我的movie_user
表格中没有添加任何内容。
在我的User.java中,我有:
@ManyToMany(mappedBy = "users")
private List<Movie> movies = new ArrayList<>();
在我的Movie.java中,我有:
@ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "movie_user",
joinColumns = @JoinColumn(name = "movie_id"),
inverseJoinColumns = @JoinColumn(name = "user_id")
)
private List<User> users = new ArrayList<>();
在我的MySQL工作台中,我看到一个包含2列的movie_user
表:movie_id
和user_id
。当我保存电影时,该表没有任何反应。
这是服务器的输出:
2017-11-07 20:35:04.491 INFO 8140 --- [nio-8090-exec-1] c.m.s.JwtAuthenticationTokenFilter : checking authentication f├╝r user admin
2017-11-07 20:35:04.491 INFO 8140 --- [nio-8090-exec-1] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select user0_.id as id1_3_, user0_.email as email2_3_, user0_.enabled as enabled3_3_, user0_.firstname as firstnam4_3_, user0_.lastpasswordresetdate as las
tpass5_3_, user0_.lastname as lastname6_3_, user0_.password as password7_3_, user0_.username as username8_3_ from user user0_ where user0_.username=?
Hibernate: select authoritie0_.user_id as user_id1_4_0_, authoritie0_.authority_id as authorit2_4_0_, authority1_.id as id1_0_1_, authority1_.name as name2_0_1_ from
user_authority authoritie0_ inner join authority authority1_ on authoritie0_.authority_id=authority1_.id where authoritie0_.user_id=?
2017-11-07 20:35:04.514 INFO 8140 --- [nio-8090-exec-1] c.m.s.JwtAuthenticationTokenFilter : authenticated user admin, setting security context
Hibernate: select movie0_.id as id1_1_1_, movie0_.name as name2_1_1_, users1_.movie_id as movie_id1_2_3_, user2_.id as user_id2_2_3_, user2_.id as id1_3_0_, user2_.em
ail as email2_3_0_, user2_.enabled as enabled3_3_0_, user2_.firstname as firstnam4_3_0_, user2_.lastpasswordresetdate as lastpass5_3_0_, user2_.lastname as lastname6_
3_0_, user2_.password as password7_3_0_, user2_.username as username8_3_0_ from movie movie0_ left outer join movie_user users1_ on movie0_.id=users1_.movie_id left o
uter join user user2_ on users1_.user_id=user2_.id where movie0_.id=?
Hibernate: select tbl.next_val from hibernate_sequences tbl where tbl.sequence_name=? for update
Hibernate: update hibernate_sequences set next_val=? where next_val=? and sequence_name=?
Hibernate: insert into movie (name, id) values (?, ?)
所以看起来hibernate正在用表做一些事情,但我不确定我现在该做什么。 This is the tutorial that I followed
答案 0 :(得分:0)
教程说,
如果使用双向,则必须使用添加/删除实用程序方法 协会,以便你可以确保双方的 关联是同步的。
你需要像教程中的方法addTag
和removeTag
一样,因为Hibernate不会自动填充。例如
class User {
public void addMovie(Movie movie) {
movies.add(movie);
movie.getUsers().add(this);
}
}
因此,不要多关注教程,一切都会有效