我捕获了json响应,我发现它是{“page”:“1”,“total”:“2”,“records”:“15”,“rows”:[{“id”:1 “名字”: “约翰”, “姓氏”: “史密斯”, “用户名”: “约翰”, “密码”: “21232f297a57a5a743894a0e4a801fc3”, “角色”:空},{ “ID”:2, “名字” : “简”, “姓氏”: “亚当斯”, “用户名”: “简”, “密码”: “ee11cbb19052e40b07aac0ca060c23ee”, “角色”:空},
我的用户和角色类非常简单,所以我认为我必须忽视一些微不足道的事情。
@Entity(name="user")
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
@Column(unique=true)
private String username;
private String password;
@JsonIgnore
@OneToMany(mappedBy="user", cascade={CascadeType.PERSIST, CascadeType.MERGE},fetch =FetchType.EAGER)
private List<Role> roles = new ArrayList<Role>();
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
@ManyToOne
private Role role;
public User() {}
public User(String username, String password, String firstName, String lastName, Role role) {
this.username = username;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.role = role;
}
public User(String username, String firstName, String lastName, Role role) {
this.username = username;
this.firstName = firstName;
this.lastName = lastName;
this.role = role;
}
public User(String username) {
this.username = username;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
@Entity(name="role")
public class Role implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@JsonIgnore
@ManyToOne
@JoinColumn (name = "user_id", nullable= true)
private User user;
private Integer role;
public Role() {}
public Role(Integer role) {
this.role = role;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
}
我也尝试了
@JsonUnwrapped @ManyToOne私人角色角色;
但这更糟糕,因为在这种情况下我的json根本没有角色。 { “ID”:1, “名字”: “约翰”, “姓氏”: “史密斯”, “用户名”: “约翰”, “密码”: “21232f297a57a5a743894a0e4a801fc3”},
答案 0 :(得分:0)
由于复杂的遗留关系要求(即用户具有角色和角色),我在将对象作为响应传回之前错误地操作了对象。
@JsonUnwrapped只能在子对象中有属性时解包,因此它按预期工作。