JPA with Hibernate - Many to Many relationship, fetching all data

为君一笑 提交于 2019-12-21 06:28:08

问题


I have many to many relation ship between User and Roles. For example

public class User {
   @Id
   private Integer id;

   @ManyToMany
   @JoinTable(name = "APP_USER_ROLE", 
     joinColumns = { @JoinColumn(name = "USER_ID") }, 
     inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
   private List<Role> roles = new ArrayList<Role>();
}

@Entity     
public class Role {
  @Id
  private Integer id;

  @ManyToMany(mappedBy = "roles")
  private List<User> users = new ArrayList<User>();
}

My requirement is to fetch all users in the system with their roles. When using HQL using this my query is

select u, u.roles from User u

however this fires a query for every user with corresponding roles. If there are 100 users, it will fire 100 queries. However in SQL I can achieve it using follwing query

select u.id, 
u.name, m.roleId, r.name FROM User u left outer join UserRole m ON u.id = m.userId 
inner join Roles r ON m.roleId = r.id  
order by u.id;

I am doing left outer join for user as there are some user who have no associated roles. I prefer not to use native SQL as it has its own disadvantages. Could some one help me to map corresponding HQL or JPQL query?


回答1:


Try this query

select u from User u left join fetch u.roles


来源:https://stackoverflow.com/questions/26358189/jpa-with-hibernate-many-to-many-relationship-fetching-all-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!