I have two entities, user and role with a many-to-many mapping, I maintain a join table entity called users_roles to maintain some other rel fields,
// ignored trivial fields
@Entity
public class User {
private name;
@OneToMany
private List<UsersRoles> usersRoles;
}
@Entity
public class Role {
private name;
@OneToMany
private List<UsersRoles> usersRoles;
}
@Entity
public class UsersRoles {
@ManyToOne
private List<User> users;
@ManyToOne
private List<Role> roles;
// other fields like tenantId
}
What’s the proper way to fetch a user by name, if I do
public interface UserRepository extends JpaRepository<User, Long>{
Optional<User> getReferenceByName(String name);
}
I get the user object with the usersRoles object, but the usersRoles object contains the users, which in turn contains usersRoles and loops around infinitely.
Ultimately, I have to fetch a user with his role names, I don’t actually need the usersRoles object, it’s solely introduced to maintain tenantId field for multitenancy. I’ve a similar dependency with roles and privileges, not sure how to resolve it.
Most of the solutions introduce a DTO to solve the problem, I would need a DTO like the following, but not sure how to map a query to this DTO. I’m fairly new to JPA, so if it’s a redundant question kindly point me to the solution.
public class UserDTO {
private name;
private List<Role> roles;
}