我的專案中基本上有用戶和角色物體。
@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>();
}
這是我的控制器類
@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 類
@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中保存的資料是這樣的

我的錯誤在哪里?提前感謝您的回答。
uj5u.com熱心網友回復:
你有“回圈依賴”。用戶有角色,角色有用戶等。您可能應該首先將物體映射到 DTOS,然后添加@JsonManagedReference或@JsonBackReference。
或者你可以簡單地@JsonIgnore穿上private List<User> users= new ArrayList<User>();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/431808.html
