【发布时间】:2023-04-08 19:07:01
【问题描述】:
面对这个
无法写入 JSON:org.hibernate.collection.internal.PersistentSet 无法转换为 org.springframework.security.core.GrantedAuthority;嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException: org.hibernate.collection.internal.PersistentSet 不能转换为 org.springframework.security.core.GrantedAuthority (通过引用链:java.util.ArrayList[0]-> com.example.springboot.model.User["authorities"])
尝试将用户列表传递到我的 html 页面时出错。
我想关键是角色类的序列化错误,但我不知道如何解决这个问题。
两个类都在下面。 User 和 Role 类与 ManytoMany 模型相连。
@Entity
@Table(name = "users_for_spring_crud")
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "email")
private String email;
@Column(name = "password")
private String password;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
@Entity
@Table(name = "roles")
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Role implements GrantedAuthority {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "role_id")
private long id;
@Column(name = "role")
private String roleName;
@ManyToMany(mappedBy = "roles")
@JsonIgnore
List<User> users;
如果需要,还有一个控制器类中的方法。
@GetMapping(value = "/admin", produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public List<User> showUsersTable(@ModelAttribute("user") User user){
List<User> listUsers = userService.listUsers();
return listUsers;
考虑编写自定义序列化程序,但不知道它应该如何工作。
【问题讨论】: