So I’m getting some roles introduced in my system. I have a class that looks like this :
@Entity @Table(name = "user_role_mapping") @AllArgsConstructor @NoArgsConstructor @Data public class UserRoleMapping { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") Integer id; @Column(name = "role_id") Role role; @ManyToOne @JoinColumn(name = "user_id") User user; public UserRoleMapping(Role role, User user) { this.role = role; this.user = user; } }
The classes that are mapping by this look like as follows :
public enum Role { ROLE_CUSTOMER(1) , ROLE_ADMIN(0); public int id; private Role (int id){ } }
The user class looks like :
public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "phone") private String phoneNumber; @Column(name = "name") private String name; @OneToMany(mappedBy = "id", fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Set<UserRoleMapping> userRoles; }
For an initial POC , i wrote a simple API method that looks like :
@RequestMapping(value = "", method = RequestMethod.GET) public ResponseEntity<?> returnUserAndDefaultRole( @RequestParam(name = "phone") String phone) { User user = usersRepository.findByPhoneNumber(phone); List<UserRoleMapping> urm = userRoleMappingRepository.findAllByUser(user); UserRoleMapping userRoleMapping; if (urm.size() == 0) { userRoleMapping = new UserRoleMapping(Role.ROLE_CUSTOMER, user); userRoleMappingRepository.save(userRoleMapping); } else { userRoleMapping = urm.get(0); } Map<String, Object> result = new HashMap<>(); result.put("User", user ); result.put("Role_info" ,userRoleMapping); return new ResponseEntity<>(result, HttpStatus.OK); }
Here, I expect to get the User object which also has a Set as well as one userRoleMapping object under the Role_info
key.
My actual output looks like :
"User": { "id": 1542275, "phoneNumber": "9527725710", "name": "njari", "userRoles": [] }, "Role_info": { "id": 1, "role": "ROLE_CUSTOMER", "user": { "id": 1542275, "phoneNumber": "9527725710", "name": "njari", "userRoles": [] } } }
My Role_Info is populated. However, The userRoles within the user object isn’t. First, I want the inner Set of userRoles to be populated. Second,I also don’t want the Role_Info to include the entire User object, how do I achieve this?
Advertisement
Answer
If i am not wrong, please try changing your mapping
@OneToMany(mappedBy = "id", fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Set<UserRoleMapping> userRoles;
To:
@OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Set<UserRoleMapping> userRoles;
To exclude the field/object, i am using @JsonIgnore:
@JsonIgnore @ManyToOne @JoinColumn(name = "user_id") User user;