带有Hibernate的JPA:.... org.hibernate.QueryException:非法尝试取消引用集合

时间:2014-11-24 11:25:38

标签: sql hibernate jpa group-by spring-data-jpa

我的@ManyToMany关系描述如下:

FOO
-----------------------
FOO_ID             
    ........

FOO_BARS
--------------------
BAR_ID          
FOO_ID          

BAR
-------------------- 
BAR_ID              
    .......


@Entity
@Table(name = "FOO")
public class FOO  
{
    @Id
    @SequenceGenerator(....)
    @GeneratedValue(...)
    @Column(name = "FOO_ID", unique = true, nullable = false, precision = 10)
    private int fooId;

    public int getFooId()
    {
    ......
    }

    public void setFooId(final int fooId)
    {
    ......;
    }

    .....

    @@ManyToMany()
    @JoinTable(name = "FOO_BARS", joinColumns = { @JoinColumn(name = "FOO_ID", nullable = false) }, inverseJoinColumns = { @JoinColumn(name = "BAR_ID", nullable = false) })
    private List<Bar> bars; 

    public List<Bar> getBars()
    {
        ......
    }

    public void setBars(final List<Bar> bars)
    {
        ......
    }

    public Bar addBar(Bar value)
    {
      .....
    }
    ......
}

@Entity
@Table(name = "BAR")
public class Bar 
{
    @Id
    @SequenceGenerator(...)
    @GeneratedValue(...)
    @Column(name = "BAR_ID", unique = true, nullable = false, precision = 9)
    private int barid;

    public int getBard()
    {
        .....
    }

    public void setBarId(final int barId)
    {
        .....
    }

    .....

    @ManyToMany(mappedBy = "bar")
    private List<Foo> foos;

    public List<Foo> getFoos()
    {
        ....
    }

    public void setFooList(final List<Foo> foos)
    {
        ....
    }

    public Foo addFoo(final Foo foo)
    {
       .......
    }


.....
}

我有一个sql查询,我可以成功运行以选择匹配提供的barIds列表的所有foos。这会根据提供的barIds更改,但格式为:

SELECT f.* FROM foo f 
WHERE 
.....
AND f.foo_id IN
(
  SELECT fb.foo_id FROM foo_bars fb
            WHERE fb.bar_id IN ( 69, 332)
            GROUP BY  fb.foo_id
            HAVING COUNT(DISTINCT fb.bar_id) =  2
); 

由于权限不使用链接表,我的问题是将其转换为使用hibernate语法运行的查询。 我尝试过以下方法:

SELECT f FROM Foo AS f  
WHERE 
.....
AND f.fooId  IN  
(  
    SELECT  b.foos.fooId FROM f.bars b  
    WHERE  b.barid  IN (:barids) 
    GROUP BY  b.foos.fooId  
    HAVING  COUNT  (  DISTINCT  b.barid  )  = 2 
)  

这会导致以下错误。

org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.QueryException: illegal attempt to dereference collection [bar2_.BAR_ID.foos] with element property reference [fooId]

非常感谢任何帮助。

0 个答案:

没有答案