【问题标题】:How to retrieve data from many to many relationship in HQL, with Spring and JPA,when the joinTable is not an entity?当joinTable不是实体时,如何使用Spring和JPA从HQL中的多对多关系中检索数据?
【发布时间】:2019-07-28 14:06:36
【问题描述】:

我有一个与这个问题类似的案例 [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。我得到的只是错误

“命名参数未绑定:”。

我该如何解决?

【问题讨论】:

  • 为什么查询会有参数?阅读 hibernate 用户指南的 JPQL 章节。它有一个关于连接的完整部分。
  • 但如果没有 where 子句,我会收到错误“查询方法公共摘要的验证失败”
  • 当然,因为您的查询不是有效的 JPQL。这就是为什么我建议您阅读有关 JPQL 的文档:以便您学习该语言的语法。
  • 你能给我一个链接吗

标签: spring hibernate jpa model-view-controller hql


【解决方案1】:

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

  • 删除参数前面的空格。 所以你将拥有 (=:abc) 而不是 (=:abc)。

  • 您的查询依赖于外部参数,对指定参数使用@param 注释。 所以你会有 ".....countByRoleList(@Param("abc") long 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 页面,一个函数。您也可以手动提供...

【讨论】:

  • 请@CodIn ?
猜你喜欢
  • 2016-06-03
  • 2012-04-09
  • 2021-02-26
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
  • 2020-04-08
  • 2013-04-25
  • 2021-05-25
相关资源
最近更新 更多