背景:有两个表:CpCg与CpGg需要进行多表查询
因为CpGg表设计到与另外的表也有联系,因此师兄没有关联此两个表,只是用字段进行逻辑关联,CpGg表的cp字段与CpCg表的id字段逻辑关联
首先确保hibernate配置文件配置完成,配置文件如下:(一些与本人项目相关的关键字段已隐去)
/p>
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
com.mysql.jdbc.Driver
jdbc:mysql://localhost/efoer
root
123
20
1
5000
100
3000
2
true
org.hibernate.dialect.MySQL5InnoDBDialect
update
true
true
配置完成后,新建一个包,命名为Util,在此包下创建一个类:HibernateUtil.java。此类代码如下:
packageutil;import org.hibernate.*;import org.hibernate.cfg.*;import org.hibernate.service.*;import org.hibernate.boot.registry.*;public classHibernateUtil
{public static finalSessionFactory sessionFactory;static{try{
Configuration cfg= newConfiguration()
.configure();
ServiceRegistry serviceRegistry= newStandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build();
sessionFactory=cfg.buildSessionFactory(serviceRegistry);
}catch(Throwable ex)
{
System.err.println("Initial SessionFactory creation failed." +ex);throw newExceptionInInitializerError(ex);
}
}public static final ThreadLocalsession= new ThreadLocal();public staticSession currentSession()throwsHibernateException
{
Session s=session.get();if (s == null)
{
s=sessionFactory.openSession();
session.set(s);
}returns;
}public static voidcloseSession()throwsHibernateException
{
Session s=session.get();if (s != null)
s.close();
session.set(null);
}
}
完成以上工作以后开始在对应的controller里面写sql语句
@RequestMapping(value="/page",method=RequestMethod.GET)publicString getRole( Model model){//打开Session和事务
Session session=util.HibernateUtil.currentSession();
Transaction tx=session.beginTransaction();
String sqlString="select s.id,s.pp,s.cd,s.mc,s.lb,s.sj,s.zt,s.jc,e.id,e.cp,e.gg,e.hh,e.tm,e.cz,e.bz,e.dpcc,e.bzcc,e.sl,e.sj,e.cj,e.zt "
+"from cp_cg s, cp_gg e "
+"where s.id=e.cp "
+"and s.zt=2";
List list=session.createSQLQuery(sqlString)//指定将从S表查询得到的记录行转为CpCg实体
.addEntity("s",CpCg.class)//指定将从e表查询得到的记录行转为CpGg实体
.addEntity("e", CpGg.class)
.list();//提交事务,关闭Session
tx.commit();
util.HibernateUtil.closeSession();//因为数据已经全部被选出,故程序可以遍历列表中的数据//在控制台输出字段,为了方便自己查看查询结果
for(Object ele:list){
Object[] objs=(Object[])ele;
CpCg s=(CpCg)objs[0];
CpGg e=(CpGg)objs[1];
System.out.println(s.getCd()+s.getMc()+s.getPp()+"\t"
+e.getHh()+e.getTm()+e.getSl());
model.addAttribute("cd", s.getCd());
}//为了把数据传给前台
model.addAttribute("list", list);return "/page/pm/index";
}
个人理解:这里关联的两个表查询的,并且查询完成后将记录行转为了两个对应的实体,因此查询出来的list里的每条记录相当于由两个实体对象拼凑而成,list[0]存放的CpCg,list[1]存放的CpGg
所以在前台取值出来的时候list[0]取出的是CpCg对象,list[1]取出的是CpGg对象。代码如下:
- ${list[0].id}
- ${list[0].pp}
- ${list[0].cd}
- ${list[0].mc}
- ${list[0].jc}
- ${list[1].gg}
- ${list[1].hh}
- ${list[1].tm}
- ${list[1].cz}
但为什么查询出来的list的数据是这么存放的,个人还没想明白。希望有明白的小伙伴看到后一解本人困惑,不胜感激