我有3张表,比如
Section (id, title, url)//id is Primary key
Category (id, title)//id is Primary key
SubCategory (id, title)//id is Primary key
在这里,我想像
这样的简单查询加入这些表Select * From Category cat, Section se, SubCategory subCat WHERE
subCat.id=23456 AND subCat.category=cat.id AND subCat.section = se.id
如何在Hibernate中使用Criteria实现上述查询?能够 有人帮我这个吗?
我的实体文件如下:
@Entity
@Table(name="section")
public class SectionEntity{
private int id;
private String title;
//Getter & setter method
}
@Entity
@Table(name="category")
public class CategoryEntity{
private int id;
private String title;
private Set<SubCategoryEntity> subCategory;
//Getter & setter method
@OneToMany(cascade = CascadeType.ALL, fetch=FetchType.LAZY)
@JoinColumn(name="category", insertable=false, updatable=false)
public Set<SubCategoryEntity> getSubCategory(){
return this.subCategory;
}
}
@Entity
@Table(name="subcategory")
public class SubCategoryEntity{
private int id;
private String title;
private Set<SectionEntity> sectionEntity;
//Getter & setter method
@OneToMany(fetch=FetchType.LAZY)
@JoinColumn(name="id", insertable=false, updatable=false)
public Set<SectionEntity> getSectionEntity(){
this.section;
}
}
第1步:为类别实体创建条件 Criteria categoriesCriteria = session.createCriteria(CategoriesEntity.class,“categoryEntity”);
步骤2:创建SubCategoryEntity和SectionEntity的别名 categoriesCriteria.createAlias(“categoryEntity.subCategoryEntity”,“subCatEntity”); categoriesCriteria.createAlias(“subCatEntity.sectionsEntity”,“subCatSectionEntity”);
步骤3:在投影列表中设置属性
步骤4:添加限制为: categoriesCriteria.add(Restrictions.eq(“subCatEntity.id”,primCategoryId));
步骤5:将投影属性设置为CategoryEntity Criteria categoriesCriteria.setProjection(projPropList);
第6步:获得结果 categoriesCriteria.list();
select this_.id as y0_, this_.title as y1_, this_.sef_url as y2_, subcatenti1_.id as y3_, subcatenti1_.title as y4_, subcatenti1_.sef_url as y5_
from jos_categories this_
inner join jos_subcategories subcatenti1_ on this_.id=subcatenti1_.category
inner join jos_sections subcatsect2_ on subcatenti1_.id=subcatsect2_.id
where subcatenti1_.id=?
select this_.id as y0_, this_.title as y1_, this_.sef_url as y2_, subcatenti1_.id as y3_, subcatenti1_.title as y4_, subcatenti1_.sef_url as y5_
from jos_categories this_
inner join jos_subcategories subcatenti1_ on this_.id=subcatenti1_.category
inner join jos_sections subcatsect2_ on subcatenti1_.section=subcatsect2_.id
where subcatenti1_.id=?
我如何实现这一目标,有人可以帮助我吗?
答案 0 :(得分:0)
在你的SubCategoryFile中进行这样的改变,
1)删除&#34; private int section;&#34;以及所有的getter和setter方法。
2)并使用此
@JoinColumn(name="section", insertable=false, updatable=false)
public Set<SectionEntity> getSection(){
this.section;
}
然后尝试运行。我希望它能起作用