Victor Magalhães Victor Magalhães - 1 year ago 39
SQL Question

Spring Data Map Object

I need to join 2 tables and return data in JSON. For this thought in a HashMap, but I do not know how to do.


public class User {


public class Profile {
@JoinColumn(name = "user_id")
private User user;


public interface UserRepository extends JpaRepository<User, Long>{

public interface ProfileRepository extends JpaRepository<Profile, Long>{

I need the number of profiles per user in a list.

John 0
Victor 2
Maria 4

What better way to do this?

Answer Source

You can create a mapping table and use that table to join both table:

      joinColumns={ @JoinColumn(name="USER_ID", referencedColumnName="ID")},
      inverseJoinColumns={ @JoinColumn(name="PROFILE_ID", referencedColumnName="ID")}
private List<Profile> profileList;


  • USER_ID number
  • PROFILE_ID number

When you get user list, you can iterate it and get profile list for each of them:

ArrayList<User> userList = UserRepository .findAll();
     user.getProfileList().size();  //You can get size for each user