0

I have a RestController class with the following :

@RestController
public class UserRestController 
{
@Autowired
UserService userService;

@Autowired
private SecurityService securityService;

@Autowired
private UserValidator userValidator;

// Get a Single User
@GetMapping("/api/users/{id}")
public User getUserById(@PathVariable(value = "id") Long userId) {
    return userService.getUserById(userId);
}

This is getUserById function in UserService :

 public User getUserById(@PathVariable(value = "id") Long userId) {
    return userRepository.findById(userId).orElseThrow(() -> new ResourceNotFoundException("User", "id", userId));
}

This is the result of a GET request on localhost:8080/api/users/11 :

{
"id": 11,
"name": null,
"email": null,
"password": "$2a$10$HykDWcHU3vO9YAcdXiWieua9YyYMkwrNIk7WgpmVzVwENb71fDCsW",
"status": null,
"tel": null,
"confirmation": null,
"birth_date": null,
"createdAt": "2018-05-22T09:09:12.000+0000",
"updatedAt": "2018-05-22T09:09:12.000+0000",
"username": "ouissal@gmail.com"
}

This is the result of a GET request on localhost:8080/users/11

{
"name": null,
"email": null,
"password": "$2a$10$HykDWcHU3vO9YAcdXiWieua9YyYMkwrNIk7WgpmVzVwENb71fDCsW",
"status": null,
"tel": null,
"confirmation": null,
"birth_date": null,
"createdAt": "2018-05-22T09:09:12.000+0000",
"updatedAt": "2018-05-22T09:09:12.000+0000",
"username": "ouissal@gmail.com",
"_links": {
    "self": {
        "href": "http://localhost:8080/users/11"
    },
    "user": {
        "href": "http://localhost:8080/users/11"
    },
    "roles": {
        "href": "http://localhost:8080/users/11/roles"
    }
}
}

I do not have anything mapped for /users in my controller, how can I get the roles using my controller?


edit

This is my User class :

@Entity
@Table(name = "user")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, 
    allowGetters = true)

public class User implements Serializable{

private static final long serialVersionUID = 1L;


public User() {
    super();
    // TODO Auto-generated constructor stub
}

@Id
@Column(name = "user_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@Column(name = "user_name")
//@NotBlank
private String name;

@Column(name = "user_email")
//@NotBlank
private String email;

@Column(name = "user_password")
@NotBlank
private String password;

@Column(name = "user_status")
private String status;

@Column(name = "user_tel")
private String tel;

@Column(name = "user_confirmation")
private String confirmation;

@Column(name = "user_birth_date")
@Temporal(TemporalType.DATE)
private Date birth_date;

@Column(nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date createdAt;

@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
private Date updatedAt;

@JsonBackReference
@ManyToMany
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;

@Column(name = "username")
@NotBlank
private String username;

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public String getTel() {
    return tel;
}

public void setTel(String tel) {
    this.tel = tel;
}

public String getConfirmation() {
    return confirmation;
}

public void setConfirmation(String confirmation) {
    this.confirmation = confirmation;
}

public Date getBirth_date() {
    return birth_date;
}

public void setBirth_date(Date birth_date) {
    this.birth_date = birth_date;
}

public Date getCreatedAt() {
    return createdAt;
}

public Date getUpdatedAt() {
    return updatedAt;
}

public void setUpdatedAt(Date updatedAt) {
    this.updatedAt = updatedAt;
}

public Set<Role> getRoles() {
    return roles;
}

public void setRoles(Set<Role> roles) {
    this.roles = roles;
}
}

and this is my role class :

@Entity
@Table(name = "role")
public class Role {

@Id
@Column(name = "role_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "role_name")
private String name;
@ManyToMany(mappedBy = "roles")
@JsonManagedReference
private Set<User> users;



public Role() {
    super();
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}


public Set<User> getUsers() {
    return users;
}

public void setUsers(Set<User> users) {
    this.users = users;
}
}
Ouissal
  • 1,519
  • 2
  • 18
  • 36
  • Have you tried hitting `roles` url `http://localhost:8080/users/11/roles` are you getting roles there? – sagarr May 28 '18 at 08:49
  • Yes I do get them, but what I don't understand is why do I get them although my controller isn't mapped for /users but for /api/users. I don't know also in what way should I edit my controller to get them at /api/users/ – Ouissal May 28 '18 at 08:51
  • Can you provide the code of the `User` class? You are directly returning it as your response, therefore it also has to have the roles included if you want to see them in your json response. – Abaddon666 May 28 '18 at 08:54
  • 1
    Are you using `spring-data-rest` lib? Looks like you are following this tutorial: http://www.baeldung.com/spring-data-rest-intro – sagarr May 28 '18 at 08:54
  • @Abaddon666 I have edited my question – Ouissal May 28 '18 at 08:58
  • 1
    have a look at this answer: https://stackoverflow.com/a/37393711/2929488, i guess this this could explain why your roles are not serialized into json – Abaddon666 May 28 '18 at 09:04
  • @Abaddon666 Thank you! that has fixed my issue – Ouissal May 28 '18 at 09:12
  • You're welcome! I wrote a little answer for later visitors to see – Abaddon666 May 28 '18 at 09:19

1 Answers1

0

Properties annotated with JsonBackReference will not be included in your serialized content. To include the roles swap the JsonBackReference and JsonManagedReference annotations in Role and User.

This will include Roles into User but not the other way round.

For more information you can check this answer

Abaddon666
  • 1,533
  • 15
  • 31