Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

Spring JPA: How to fetch a Many to Many Relation, with the Join table as separate entity, without infinite recursion

$
0
0

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@Entitypublic class User {    private name;    @OneToMany    private List<UsersRoles> usersRoles;}
@Entitypublic class Role {    private name;    @OneToMany    private List<UsersRoles> usersRoles;}
@Entitypublic 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;}

Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>