我有以下实体类,
一个 AppUser 可以有 1 个个人资料和多个帖子,
1 个帖子只能与 1 个 AppUser 关联,
AppUser和Role会多对多关联。
AppUser -
@Getter
@Setter
@Entity
@Table(name = "app_user")
public class AppUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "username")
private String username;
@Column(name = "email")
private String email;
@JsonManagedReference
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "profile_id")
private Profile profile;
@JsonManagedReference
@OneToMany(mappedBy = "appUser", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Post> posts = new ArrayList<>();
@JsonBackReference
@ManyToMany
@JoinTable(
name = "user_role",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)
private Set<Role> roles = new HashSet<>();
}
Profile -
@Getter
@Setter
@Entity
@Table(name = "profile")
public class Profile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String bio;
}
Post -
@Getter
@Setter
@Entity
@Table(name = "post")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String content;
@JsonBackReference
@ManyToOne
@JoinColumn(name = "app_user_id")
private AppUser appUser;
}
Role -
@Getter
@Setter
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany(mappedBy = "roles")
private Set<AppUser> appUsers = new HashSet<>();
}
当我执行简单的 userRepository.findAll(); 时,我得到以下响应,其中未获取角色数据
// http://localhost:8080/user/all
[
{
"id": 1,
"username": "john_doe",
"email": "[email protected]",
"profile": {
"id": 1,
"bio": "This is John Doe's bio."
},
"posts": [
{
"id": 1,
"content": "Content of post 1"
},
{
"id": 2,
"content": "Content of post 2"
}
]
},
{
"id": 2,
"username": "jane_smith",
"email": "[email protected]",
"profile": {
"id": 2,
"bio": "This is Jane Smith's bio."
},
"posts": [
{
"id": 3,
"content": "Content of post 3"
}
]
}
]
@JsonManagedReference
实体中的
roles
字段使用
AppUser
,对
@JsonBackReference
实体中的
appUsers
字段使用
Role
。而且很可能您还需要在加载用户时使用
@EntityGraph(attributePaths = "roles")
以避免
LazyInitializationException
,或者您可以为
fetch = FetchType.EAGER
字段添加
roles
。