请问hql多表联合查询有关问题
请教hql多表联合查询问题
数据库建立tb_category(id,name)和tb_info(id,title,categoryId)两张表,并建立级联
Category.hbm.xml
Info.hbm.xml
在Category.java中
private Category cates; //类别
public Category getCates() {
return cates;
}
public void setCates(Category cates) {
this.cates = cates;
}
在Action类调用
InfoDao dao = new InfoDao();
med = dao.loadInfoAndCategory(Integer.parseInt(id));
在jsp页面调用
<logic:iterate id="ele" name="med" scope="request">
&{ele.name}
</logic:iterate >
name是tb_category表的字段,怎么显示为 空呢?是不是
String hql = "select a from Info a join fetch a.cates b where a.id = " + id;
有什么问题?谢谢!!
------解决思路----------------------
数据库建立tb_category(id,name)和tb_info(id,title,categoryId)两张表,并建立级联
Category.hbm.xml
<hibernate-mapping package="com.lyq.persistence">
<class name="Category" table="tb_category">
<!-- 主键 -->
<id name="id">
<generator class="native"/>
</id>
<property name="name" not-null="true" length="100"/>
<!-- 一对多关系 -->
<set name="meds" inverse="true" cascade="all" order-by="categoryId">
<key column="categoryId"/>
<one-to-many class="Info"/>
</set>
</class>
Info.hbm.xml
<hibernate-mapping package="com.lyq.persistence">
<class name="Info" table="tb_info">
<!-- 主键 -->
<id name="id">
<generator class="native"/>
</id>
<property name="title" not-null="true" />
<!-- 与类别的多对一关系 -->
<many-to-one name="cates" column="categoryId" cascade="save-update" lazy="proxy"/>
</class>
在Category.java中
private Category cates; //类别
public Category getCates() {
return cates;
}
public void setCates(Category cates) {
this.cates = cates;
}
public Info loadInfoAndCategory(int id) {
Info info = null;
try {
session = HibernateFilter.getSession(); // 获取Session对象
session.beginTransaction(); // 开启事物
// HQL查询语句
String hql = "select a from Info a join fetch a.cates b where a.id = "
+ id;
info = (Info) session.createQuery(hql) // 创建Query对象
.uniqueResult(); // 单值检索
session.getTransaction().commit(); // 提交事物
} catch (Exception e) {
e.printStackTrace(); // 打印异常信息
session.getTransaction().rollback(); // 回滚事物
}
return info;
}
在Action类调用
InfoDao dao = new InfoDao();
med = dao.loadInfoAndCategory(Integer.parseInt(id));
在jsp页面调用
<logic:iterate id="ele" name="med" scope="request">
&{ele.name}
</logic:iterate >
name是tb_category表的字段,怎么显示为 空呢?是不是
String hql = "select a from Info a join fetch a.cates b where a.id = " + id;
有什么问题?谢谢!!
------解决思路----------------------
//映射文件看出:Category类中应该有Info类的集合才对啊。Info是多、Category是一。
//hql语句当然就错了。。。把你的实体类贴出来!