Spring JPA获取ManyToMany

时间:2016-03-19 19:34:17

标签: java spring jpa spring-data spring-data-jpa

我有一个有权限的用户(ManyToMany关系):

@Entity
@Table(name = "user")
public class User {
    @JsonIgnore
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
        name = "user_authority",
        joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "user_id")},
        inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
    private Set<Authority> authorities = new HashSet<>();

}


@Entity
@Table(name = "authority")
public class Authority implements Serializable {

    @Id
    @Column(length = 50, nullable = false)
    private String name;

}

Liquibase(没有用户,他只有一个id):

<createTable tableName="authority">
        <column name="name" type="varchar(50)">
            <constraints primaryKey="true" nullable="false"/>
        </column>
    </createTable>

    <createTable tableName="user_authority">
        <column name="user_id" type="bigint">
            <constraints nullable="false"/>
        </column>
        <column name="authority_name" type="varchar(50)">
            <constraints nullable="false"/>
        </column>
    </createTable>

    <addPrimaryKey columnNames="user_id, authority_name" tableName="user_authority"/>
    ...

我必须获取所有用户权限,这等于某个名称。例如,我必须获取所有管理员(具有权限'ROLE_ADMIN'的用户)。

2 个答案:

答案 0 :(得分:1)

如果没有自定义查询,这可能有效:

List<Authority> admin_authorities = authorityRepository.findByName("ROLE_ADMIN");
List<User> admins = userRepository.findByAuthoritiesIn(admin_authorities);

答案 1 :(得分:0)

您可以按实体而不是名称直接搜索。使用MEMBER OF,您告诉JPA:“获取所有具有X实体而非X集合的实体”。

@NamedQuery(name="findByAuth",
            query="SELECT u FROM User u WHERE :auth "+
                  "MEMBER OF u.authorities")
public class User implements Serializable {

    /* ... */
}

在您的服务中:

public List<User> getByAuth(Authority auth) {
    TypedQuery<User> query = em.createNamedQuery(
                                    "findByAuth",
                                    User.class);
    query.setParameter("auth", auth);
    return query.getResultList();
}