2017-09-06 18 views
1

我有两个表,用户和帖子工作。@OneToMany双向关系不正确

@Entity 
@Table(name = "users") 
public class User { 
@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
private Long id; 
@Basic 
@NotNull 
@Column(name = "username",nullable = false,unique = true) 
private String username; 
@Basic 
@NotNull 
private String password; 

@OneToOne 
@NotNull 
@JoinColumn(name = "picture_id") 
private Picture profilePicture; 

@ManyToMany 
@JoinTable(name = "followers_users", 
     joinColumns = @JoinColumn(name = "id"), 
     inverseJoinColumns = @JoinColumn(name = "follower_id")) 
private Set<User> followers; 


@ManyToMany(mappedBy = "followers", fetch = FetchType.EAGER) 
private Set<User> following; 

@OneToMany(mappedBy = "user",cascade = CascadeType.PERSIST) 
private Set<Post> posts = new HashSet<>(); 

@OneToMany(mappedBy = "user") 
private Set<Comment> comments; 

...

也:它们与多对一/一对多链接

@Entity 
@Table(name = "posts") 
public class Post { 
@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
private Long id; 

@NotNull 
@Basic 
private String caption; 

@NotNull 
@ManyToOne 
@JoinColumn(name = "user_id",referencedColumnName = "id") 
private User user; 

@NotNull 
@ManyToOne 
@JoinColumn(name = "picture_id") 
private Picture picture; 

@OneToMany(mappedBy = "post") 
private Set<Comment> comments; 

...

当我坚持用户的新职位,user.posts是空的。这不是我所期望的。我希望这会在添加新帖子时自动更新。

回答

0

我发现这个问题, 的问题是,在Controller类我把注释@Transactional。 要正常工作@Transactional需要删除。