package pojo; import java.util.HashSet; import java.util.Set; import com.fasterxml.jackson.annotation.JsonIgnore; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.ManyToMany; import jakarta.persistence.Table; @Entity @Table(name = "bluser") public class BLUser { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; @ManyToMany(cascade = CascadeType.ALL, mappedBy = "users", fetch = FetchType.LAZY) private Set public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set return roles; } public void setRoles(Set this.roles = roles; } } package pojo; import java.util.HashSet; import java.util.Set; import com.fasterxml.jackson.annotation.JsonIgnore; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.JoinTable; import jakarta.persistence.ManyToMany; import jakarta.persistence.Table; @Entity @Table(name = "blrole") public class BLRole { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; @JsonIgnore @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY) @JoinTable(name = "user_role", inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) private Set public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set getUsers() { return users; } public void setUsers(Set users) { this.users = users; } } @RestController @RequestMapping("/bl") public class BLUserRoleController { @Autowired BLUserRoleService service; @PostMapping("/finduser") public BLUser findBLUser(int id) { return service.findById(id); } } |
如果不加@JsonIgnore,就会出现BLUser.roles>BLRole.users->BLUSER.roles----- Hibernate无限循环一直取下去。@JsonIgnore告诉hibernate忽略json转换时数据抽取。