添加到双向ManyToMany集合中将检索所有已经相关的条目

时间:2019-02-26 01:22:50

标签: hibernate jpa many-to-many

我有UserGroup实体中的用户映射的User实体

USER.java

@ManyToMany(mappedBy = "users")
private Set<UserGroup> userGroups;

public void addGroup(UserGroup userGroup){
this.userGroups.add(userGroup);
userGroup.addUser(this);
}

UserGroup.java

@ManyToMany
@JoinTable(name = "group_users", joinColumns = @JoinColumn(name = "group_id"),
        inverseJoinColumns = @JoinColumn(name = "user_id"))
private Set<User> users;

public void addUser(User user) {
   this.users.add(user);
}

我有一种方法可以在UserService中将组添加到User:

@Transactional
public void addGroupsToUser(UserAddGroupsCommand userAddGroupsCommand, String username) {
    User user = userRepository.findByUsername(username);
    if (user != null) {
        List<UserGroup> userGroupList = userGroupRepository.findAllById(userAddGroupsCommand.getId());
        for (UserGroup userGroup : userGroupList) {
            user.addGroup(userGroup);
        }
        userRepository.save(user);
    }
}

问题是当我遍历组并将用户添加到每个组时,由于某种原因,Hibernate选择了该组中的所有用户(从连接表中)。

Hibernate: 
select
    users0_.group_id as group_id1_3_1_,
    users0_.user_id as user_id2_3_1_,
    user1_.id as id1_7_0_,
    user1_.email as email2_7_0_,
    user1_.firstname as firstnam3_7_0_,
    user1_.is_admin as is_admin4_7_0_,
    user1_.lastname as lastname5_7_0_,
    user1_.password as password6_7_0_,
    user1_.username as username7_7_0_ 
from
    group_users users0_ 
inner join
    user user1_ 
        on users0_.user_id=user1_.id 
where
    users0_.group_id in (
        select
            usergroup0_.id 
        from
            user_group usergroup0_ 
        where
            usergroup0_.id in (
                ? , ?
            )
    )

如何避免这种情况?有什么选择可以避免这种情况,而无需编写自己的查询,仅使用注释和JPA Repository方法即可?

1 个答案:

答案 0 :(得分:0)

添加组时有2个选择:

用于在用户呼叫{2: [[1, 3], [4, 7]], 4: [[3, 4, 7, 9], [2, 4, 5, 3]], 3: [[5, 7, 4]]} 中获取组

user.getUserGroups().add(group)

用于在组呼叫select usergroups0_.user_id as user_id2_0_0_, usergroups0_.group_id as group_id1_0_0_, usergroup1_.id as id1_8_1_ from group_users usergroups0_ inner join UserGroup usergroup1_ on usergroups0_.group_id=usergroup1_.id where usergroups0_.user_id=? 中获取用户

group.addUser(user)

users字段需要初始化,无论您是懒加载还是急于加载。