Reputation: 665
Hi I just need a HQL query to reference join column in self join.when i am trying to access join column it is throwing an exception unable to resolve category_id.Thanks in advance.
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;
}
}
This is my Manager class where i am trying to get all the sub categories of a category by referencing join column(in my case "category_id").
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);
}
}
}
Upvotes: 0
Views: 2631
Reputation: 691695
HQL works on entities, their persistent fields, and their associations. Never on table and column names. So your HQL is invalid: there is no persistent field named category_id
in the entity SubCategory
.
What you want is
select s.category_name from SubCategory s where s.category.id = 17
Note that you're not respecting the Java naming conventions, which also increases your confusion between table columns and entity fields. The category_name
field should be renamed to categoryName
, or simply name
. The query would thus become
select s.name from SubCategory s where s.category.id = 17
Upvotes: 2