1 public List dzcx(Object a) { 2 try{ 3 4 //Query p=getSession().createQuery("PersonInf where name=:name "); 5 Query p=getSession().createQuery("select p.name,p.age,a.addressDetail from PersonInf as p" + 6 " inner join p.addressInfs as a" + 7 " where a.addressDetail=:a" ); 8 //要加上select就要加上别名 9 //多个表之间查询加上 inner join 10 p.setParameter("a", a); 11 return p.list(); 12 } 13 catch(RuntimeException e) 14 { 15 log.error("find Name failed", e); 16 throw e; 17 }
select p.name,p.age,a.addressDetail from PersonInf as p inner join p.addressInfs as a where a.addressDetail=:a
这里是根据地址查询,显示名字、年龄、地址。 inner join 自动连接中间表,根据p.addressInfs 找到addressInf表。
调用查询:
<%
PersonInfDAO p=new PersonInfDAO();
List a=p.dzcx("垫江");
Iterator it=a.iterator();
while(it.hasNext()){
Object[] pit=(Object[])it.next();//注意如果返回的是一个值,而不是一个数组,那么这里就应该是Object pit=(Object)it.next();
out.print(pit[0]);
out.print(pit[1]);
out.print(pit[2]);
}
%>