Hql加入和按问题分组

时间:2010-12-29 11:29:55

标签: java hibernate hql

我正在尝试在hql中进行查询。我有这些豆子:

Bean1

@Entity
@Table(name = "bean1")
public class Bean1 {

        ...
        private List<Bean2> bean2;
...
@ManyToMany(
            cascade={CascadeType.ALL},  
            fetch=FetchType.LAZY)
@JoinTable( 
            name="bean1_bean2", 
            joinColumns=@JoinColumn(name="bean1_id"),   
            inverseJoinColumns=@JoinColumn(name="bean2_id") 
    )   
    public List<Bean2> getBean2() {
        return bean2;
    }

    public void setTags(List<Bean2> bean2) {
        this.bean2 = bean2;
    }


    ...
    }

Bean2

@Entity
@Table(name = "bean2")
public class Bean2 {

    private String bean2_id;    
    private List<Bean1> bean1;

    @Id
    @Column(name = "bean2_id", length = 100, unique = true, nullable = false)   
    public String getBean2_id() {
        return bean2_id;
    }
    public void setBean2_id(String bean2_id) {
        this.bean2_id = bean2_id;
    }

    @ManyToMany(
            cascade = {CascadeType.PERSIST, CascadeType.MERGE},
            fetch=FetchType.LAZY,
            mappedBy = "bean2"            
    )
    public List<Bean1> getBean1() {
        return bean1;
    }
    public void setBean1(List<Bean1> bean1) {
        this.bean1 = bean1;
    }

} 

查询:

Query query = session.createQuery("SELECT bean1 FROM " +
                             ((Class) Bean1.class.getName() + " bean1 " +                           
                            " WHERE " + "bean1.bean1_id=? " + 
                            " JOIN bean1.bean2.bean2_id=?" + 
                            " GROUP BY bean1.bean2"
                            );

但我得到了这个例外:

  

org.springframework.orm.hibernate3.HibernateQueryException:   非法企图取消引用   集合

我尝试了其他查询:

Query query = session.createQuery("SELECT beab1.bean2 FROM " + ((Class) Bean1.class.getName() + " bean1 " + " JOIN bean1.bean2 " + "bean2" + " WHERE " + "bean1.bean1_id=? " + " AND bean2.bean2_id=? " + " group by bean1.bean2.bean2_id=?");

另一个例外:

  

org.springframework.orm.hibernate3.HibernateQueryException:   非法企图取消引用   集合[bean10_.bean1_id.bean2]   使用元素属性引用   [bean2_id]

我真正想要的是在给定bean1_id的同一bean1中重复多少bean2_id。
我是以正确的方式吗? Hibernate 3.6.0 提前致谢

1 个答案:

答案 0 :(得分:2)

如果我理解你的问题,你应该这样做:

select b1 from Bean1 as b1 join b1.bean2 as b2 where b1.id = ?1 and b2.id= ?2 group by b2.id

然而,这可能不会起作用,因为你必须通过select中的某些东西进行分组。

但以下情况应该有效:

select b2.id from Bean1 as b1 join b1.bean2 as b2 where b1.id = ?1 and b2.id= ?2 group by b2.id

如果你想获取b1,但要按b2.id分组,你可以尝试这样的事情:

select b1, b2.id from Bean1 as b1 join b1.bean2 as b2 where b1.id = ?1 and b2.id= ?2 group by b2.id

请注意,您将在Bean1的索引为0的结果中获取数组。