I have basicly user and role entities 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>();
}
This is my controller 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());
}
And this is my 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() ;
}
}
When I request http://localhost:8080/api/users, I get wrong data like this
[{"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"}]}]}]}]
But the data saved in the db is like this
Where is my mistake? Thanks in advance for your answers.
CodePudding user response:
You have 'circular dependency'. User has roles, the role has users, etc. You should probably first map entities to DTOS and then maybe add @JsonManagedReference
or @JsonBackReference
.
Or you can simply put @JsonIgnore
on private List<User> users= new ArrayList<User>();