【问题标题】:Spring JPA fetch ManyToManySpring JPA 获取多对多
【发布时间】:2016-03-19 19:34:17
【问题描述】:

我有一个具有权限的用户(多对多关系):

@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”权限的用户)。

【问题讨论】:

  • 我认为你的 JPA 映射是错误的。您在其中一个实体中使用 @ManyToMany 注释,但在另一个实体中没有。
  • 这段代码来自 JHipster,所以我认为不是。

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


【解决方案1】:

如果没有自定义查询,这可以工作:

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

【讨论】:

    【解决方案2】:

    您可以直接按实体而不是名称进行搜索。使用 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();
    }
    

    【讨论】:

    • 我不应该使用实体管理器,所以我尝试了 JpaRepository 的查询:@Query("SELECT u FROM User u WHERE ?1 MEMBER OF u.authorities")。结果是:org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [ROLE_ADMIN] did not match expected type [com.test.model.Authority (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [ROLE_ADMIN] did not match expected type [com.test.model.Authority (n/a)]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 2015-05-10
    • 2020-03-29
    • 2020-05-12
    • 2018-10-31
    • 2016-06-03
    相关资源
    最近更新 更多