Reputation: 132
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.
@Entity
public class User {
//...
}
@Entity
public class Profile {
@JoinColumn(name = "user_id")
@ManyToOne
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
...
Upvotes: 0
Views: 626
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:
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