Victor Magalhães
Victor Magalhães

Reputation: 132

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?

Upvotes: 0

Views: 626

Answers (1)

John Lash
John Lash

Reputation: 114

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
}

Upvotes: 1

Related Questions