当 joinTable 不是实体时,如何使用 Spring 和 JPA 从 HQL 中的多对多关系中检索数据?

How to retrieve data from many to many relationship in HQL, with Spring and JPA,when the joinTable is not an entity?

我和这个问题有类似的情况[a link] (How do I do with HQL, many to many?) 我想要每个角色(实体 2)的用户数(实体 1)。我在用户和角色之间定义了多对多关系。

我正在使用 Spring MVC、Hibernate、MySQL 和 JPA。

实体 1:用户

@Entity(name = "user")
    public class User {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String email;
 @ManyToMany(mappedBy = "user")
    private List<Role> role;

实体 2:角色

@Entity
@Table(name = "role")
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int ID;
    private String libelle;
    @ManyToMany
    @JoinTable(
            name = "user_role",
            joinColumns = { @JoinColumn(name = "ID_role") },
            inverseJoinColumns = { @JoinColumn(name = "id_user") }
    )
    private List<User> user;

JPA 存储库

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
 @Query(value = "select new map( count(u.id) as numberOfUsers,r.libelle as roleLibelle )  FROM user  u join  role r where r.ID =: ????  group by r.libelle")
    List<Object> countByRoleList();

我想弄清楚 =:id 在我提到的问题中提出了什么,必须符合我的情况。而不是“????”我试过 ID,id,ID_role。我得到的只是错误

"Named parameter not bound : ".

我该如何解决?

我想你的参数类型很长。它的名字是 abc,它指的是一个 id。 请按照以下步骤操作:

  • 去掉参数前面的space。 所以你会有 (=:abc) 而不是 (=: abc).

  • 您的查询依赖于一个外部参数,对指定的参数使用@param 注释。 所以你会有 “.....countByRoleList(@Param("abc") 长 id );”

代码示例

@Repository
public interface UserRepository extends JpaRepository<User,Long> {
@Query(value = "select new map( count(u.id) as numberOfUsers,r.libelle as roleLibelle )  FROM user  u join  role r where r.ID =:abc  group by r.libelle")
List<Object> countByRoleList(@Param("abc") long id);

注意:abc 是提供的参数。它可以来自 HTML 页面,一个函数。您也可以手动提供...