manytomany连接列上的Hibernate子查询无法按预期工作

时间:2016-07-28 04:15:59

标签: javascript hibernate hql

所以我有一个非常简单的架构,我正在尝试选择*用户所关注的文章。

  1. 用户
  2. 用户可以关注其他用户

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name="userId")
    private int userId;
    @JsonIgnore
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "user_followers",
            joinColumns = {@JoinColumn(name = "user_id")}, inverseJoinColumns = {@JoinColumn(name = "following_id")})
        private Set<User> following = new HashSet<User>();
    
    1. 文章
    2. 一篇文章包含文章信息+ ManyToOne 用户字段:

      @Entity
      @Table(name="entry")
      public class Article implements Serializable {
      @ManyToOne(fetch = FetchType.EAGER)
      @JoinColumn(name = "user_id", nullable = false)
      private User userId;
      
      @Column(name="articleInfo")
      private String articleInfo
      

      这是我试图选择*文章的查询 - &gt;现在,此查询将仅选择特定:user所做的文章(请求数据的用户)。

      Query q = sess.createQuery("from Article a where a.userId IN (from a.userId.following uf where uf.userId " +
                      "= :user)");
      
      q.setParameter("user", u.getUserId());
      

      但是当我尝试只选择uf.followingId时会抛出一个异常,说明字段followId不存在?!如此处所示 - &gt;

      {@JoinColumn(name = "user_id")}, inverseJoinColumns = {@JoinColumn(name = "following_id")})
      

      您可以看到 user_id (关注的用户 - &gt; following_id)和 follower_id (被关注的用户)。

      我不明白为什么 我可以 执行uf.userId 而不是 {{1 (我也试过了uf.following_id)。

      uf.followingId

      引发以下错误:

       Query q = sess.createQuery("from Article a where a.userId IN (select uf.followingId from a.userId.following uf where uf.userId " +
                          "= :user)");
      q.setParameter("user", u.getUserId());
      

1 个答案:

答案 0 :(得分:0)

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_followers",
        joinColumns = {@JoinColumn(name = "user_id")}, inverseJoinColumns = {@JoinColumn(name = "following_id")})
    private Set<User> following = new HashSet<User>();

在上面的代码中我可以看到你正在使用HQL,属性“follow”是一个属于中间表的集合。它既不是实体用户的直接变量,也不是外键。这就是为什么你超越异常的原因。在HQL中,您必须显式触发连接查询以从JoinTable获取详细信息。

相关问题