HQL用于在自联接中引用连接列

时间:2014-06-16 09:47:51

标签: hibernate

您好我只需要一个HQL查询来引用自联接中的连接列。当我尝试访问连接列时,它会抛出异常,无法提前解析category_id.Thanks。

package com.rst;

 import java.util.HashSet;
 import java.util.Set;

 import javax.persistence.CascadeType;
 import javax.persistence.Entity;
 import javax.persistence.GeneratedValue;
 import javax.persistence.Id;
 import javax.persistence.JoinColumn;
 import javax.persistence.ManyToOne;
 import javax.persistence.OneToMany;
 import javax.persistence.Table;

 import org.hibernate.annotations.GenericGenerator;
 import org.hibernate.annotations.Parameter;

 @Entity
 @Table
 public class SubCategory {
@Id
@GeneratedValue(generator="Category_Sequence_StyleGenerator")


private int subCategory_id;

private String category_name;

@ManyToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "category_id")
private SubCategory category;

@OneToMany(mappedBy = "category")
private Set<SubCategory> set = new HashSet<SubCategory>();

public SubCategory() {
    super();
    // TODO Auto-generated constructor stub
}

public SubCategory(String category_name) {
    super();
    this.category_name = category_name;
}

public String getCategory_name() {
    return category_name;
}

public void setCategory_name(String category_name) {
    this.category_name = category_name;
}

public SubCategory getCategory() {
    return category;
}

public void setCategory(SubCategory category) {
    this.category = category;
}

public Set<SubCategory> getSet() {
    return set;
}

public void setSet(Set<SubCategory> set) {
    this.set = set;
}

}

这是我的Manager类,我试图通过引用连接列来获取类别的所有子类别(在我的情况下&#34; category_id&#34;)。

package com.rst;

 import java.util.List;

 import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;

 public class CategoryManager {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    SessionFactory sessionFactory;
    try {
        sessionFactory = Util.getSessionFactory();
    }
    catch(Throwable th){
        System.out.println("some error"+th);
        throw new ExceptionInInitializerError();
    }

    Session session = sessionFactory.openSession();

    Query q = session.createQuery(
              "select s.category_name from SubCategory s where s.category_id = 17");
    List<String> lst = q.list();
    for(String str:lst){
        System.out.println(str);
    }
}

}

1 个答案:

答案 0 :(得分:2)

HQL适用于实体,持久字段及其关联。表名和列名从不。因此,您的HQL无效:实体category_id中没有名为SubCategory的持久字段。

你想要的是

 select s.category_name from SubCategory s where s.category.id = 17

请注意,您不尊重Java命名约定,这也会增加表列和实体字段之间的混淆。 category_name字段应重命名为categoryName,或简称为name。因此查询将成为

select s.name from SubCategory s where s.category.id = 17