Victor Magalhães Victor Magalhães - 5 months ago 16
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.

User



@Entity
public class User {
//...
}


Profile



@Entity
public class Profile {
@JoinColumn(name = "user_id")
@ManyToOne
private User user;
//...
}


Repositories



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

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

@OneToMany(fetch=FetchType.LAZY)
@JoinTable
(
      name="USER_PROFILE",
      joinColumns={ @JoinColumn(name="USER_ID", referencedColumnName="ID")},
      inverseJoinColumns={ @JoinColumn(name="PROFILE_ID", referencedColumnName="ID")}
)
private List<Profile> profileList;

USER_PROFILE table:

  • 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();
for(user:userList)
{
     user.getProfileList().size();  //You can get size for each user
}
Comments