Spring关于我项目中的findAll()函数错误

Spring about findAll() function error in my project

我的项目中基本上有用户和角色实体。

@Entity
@Table(name="`User`")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String username;
    private String password;
    @ManyToMany(fetch = EAGER)
    private Collection<Role> roles = new ArrayList<>();
}

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    @ManyToMany(mappedBy = "roles")
    private List<User> users= new ArrayList<User>();

}

这是我的控制器class

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class UserResource {
    private final UserService userService;

     @GetMapping("/users")
    public ResponseEntity<List<User>> getUsers(){

        return ResponseEntity.ok().body(userService.getUsers());
    }

这是我的 UserManager class

@Service @RequiredArgsConstructor @Transactional @Slf4j
public class UserManager implements UserService {
    private final UserRepo userRepo;
    private final RoleRepo roleRepo;

     @Override
    public List<User> getUsers() {
        log.info("Fetching all users {}" );
        return userRepo.findAll() ;
    }
}

当我请求 http://localhost:8080/api/users 时,我得到了这样的错误数据

[{"id":5,"name":"Emirhan Ay","username":"emrhn1888","password":"1234","roles":[{"id":1,"name":"ROLE_USER","users":[{"id":5,"name":"Emirhan Ay","username":"emrhn1888","password":"1234","roles":[{"id":1,"name":"ROLE_USER","users":[{"id":5,"name":"Emirhan Ay","username":"emrhn1888","password":"1234","roles":[{"id":1,"name":"ROLE_USER","users":[{"id":5,"name":"Emirhan Ay","username":"emrhn1888","password":"1234","roles":[{"id"}]}]}]}]

但是db中保存的数据是这样的

我的错误在哪里?预先感谢您的回答。

您有 'circular dependency'。用户有角色,角色有用户等。您可能应该首先将实体映射到 DTOS,然后可能添加 @JsonManagedReference@JsonBackReference.

或者您可以简单地将 @JsonIgnore 放在 private List<User> users= new ArrayList<User>();