我有两个表,用户和帖子。它们与ManyToOne / 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 :(得分:0)
我发现了问题, 问题是在Controller类中我放了注释@Transactional。 要正常工作,需要删除@Transactional。