SSH框架的多表查询(方法二)

 必须明本文章==》http://www.cnblogs.com/zhu520/p/7773133.html 

 

一:在前一个方法(http://www.cnblogs.com/zhu520/p/7774144.html)一对多的查询中,我使用的是一对多的映射来查询数据的

如:一种品种类型(TbType)有多种花(TbFlower)

1):Po对象:

要在 1 的那方 包含  多的  

TbType.java

    private Integer typeId;
    private String type; 
    private Set<TbFlower> setFlowers=new HashSet<TbFlower>();  
    public Set<TbFlower> getSetFlowers() {
        return setFlowers;
    } 
    public void setSetFlowers(Set<TbFlower> setFlowers) {
        this.setFlowers = setFlowers;
    }

2):而在多那方就要:引用一的类

 TbFlower.java

private Integer flowerId;
    private String flower;
    private Integer typeId;  
     //花的品种
     private TbType tbType; 

 (1)  一般一个实体类对应一个映射文件

 3):映射文件

TbFlower.hbm.xml

TbType.hbm.xml

  一对多和多对一的映射原理是一样的,都是在多的一端加入一个外键指向一的一端

    它们的区别在于维护的关系不同

 多对一维护的关系:多指向一的关系,如果维护了多指向一的关系,那么加载多的时候会把一加载上来

 一对多维护的关系:一指向多的关系,如果维护了一指向多的关系,那么加载一的时候会把多加载上来

其实这两者什么鬼关系我也是懵逼的。。半懂又不懂的感觉。

4):然后就可以根据你需要进行你的增删查改了

二: 现在我不使用上面的映射来进行查询,我是在已有的 品种(TbType),花(TbFlower) 的基础上在新建一个po的类,它是把品种(TbType)和花(TbFlower)的变量全部组合其他来(TbFlowerTypeVo.java)

步骤:

1):我的运行环境

我使用myeclipse(你也可以使用eclipse个人喜欢),tomcat7

jar包 放在百度云,托到文章最后有链接下载即可(其实也可以根据我之前http://www.cnblogs.com/zhu520/p/7772823.html 去弄,不需要去网上下载(但是只是对myeclipse而言,eclipse还是要到网上下载的))

1): 先看看package情况先

2):applicationContext.xml 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/aop   
    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.1.xsd  
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"
    default-autowire="byName">
    
    <!-- 开启注解 -->
    <context:annotation-config />
    <!-- spring 扫描路径,注意当前工程只需要扫描dao和service,srpingmvc或者struts2注解才有变化 -->
    <context:component-scan base-package="zhu.dao,zhu.service" />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver">
        </property>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/jdbc01">
        </property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">
                    true
                </prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>

            </props>
        </property>
          <!-- 第一种方法: <property name="mappingDirectoryLocations"> 
            <list> 
            <value>classpath:zhu/cfg/</value> 
            </list> 
            </property> -->

        <!--第二种方法: -->
        <property name="mappingResources">
            <list>
                <value>zhu/cfg/TbFlower.hbm.xml</value>
                <value>zhu/cfg/TbType.hbm.xml</value>
            </list>
        </property>
    </bean>
    <!-- 配置声明式事务管理(采用注解的方式) -->
    <bean id="txManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 开启注解事务 --> <!-- 用注解来实现事务管理 -->
    <tx:annotation-driven transaction-manager="txManager" />
</beans>
applicationContext.xml

web。xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name></display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:applicationContext*.xml
        </param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
          org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
      </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>*.action</url-pattern>
  </filter-mapping>
</web-app>
web.xml

3):po包的情况

TbFlower.java ==>是没有 TbType的变量的

package zhu.po;

public class TbFlower {
    private Integer flowerId;
    private String flower;
    private Integer typeId;   
    public Integer getFlowerId() {
        return flowerId;
    }
    public void setFlowerId(Integer flowerId) {
        this.flowerId = flowerId;
    }
    public String getFlower() {
        return flower;
    }
    public void setFlower(String flower) {
        this.flower = flower;
    }
    public Integer getTypeId() {
        return typeId;
    }
    public void setTypeId(Integer typeId) {
        this.typeId = typeId;
    } 

}
TbFlower.java

 TbType.java ==》没有TbFlower

 

package zhu.po;

import java.util.HashSet;
import java.util.Set;
 
 
public class TbType {
    private Integer typeId;
    private String type; 
 
    
    public Integer getTypeId() {
        return typeId;
    }

    public void setTypeId(Integer typeId) {
        this.typeId = typeId;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}
TbType.java

 TbFlowerTypeVo.java==》这个是把上面的两个类全部变量的组合(2个以上的表也可以这样做,测试过是行的通的)

package zhu.po;

public class TbFlowerTypeVo {
    private Integer flowerId;
    private String flower;
    private Integer typeId; 
    private String type;

    public TbFlowerTypeVo(){}
    
    public TbFlowerTypeVo(int flowerId,String flower,int typeId, String  type){ 
        this.flowerId=flowerId;
        this.flower=flower;
        this.typeId=typeId;
        this.type=type; 
    }

    public Integer getFlowerId() {
        return flowerId;
    }

    public void setFlowerId(Integer flowerId) {
        this.flowerId = flowerId;
    }

    public String getFlower() {
        return flower;
    }

    public void setFlower(String flower) {
        this.flower = flower;
    }

    public Integer getTypeId() {
        return typeId;
    }

    public void setTypeId(Integer typeId) {
        this.typeId = typeId;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }     
}

  4):映射文件  只需要映射 TbFlowe和TbType不需要映射TbFlowerTypeVo

TbType.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping>
    <class name="zhu.po.TbType" table="tbtype" catalog="jdbc01">
        <id name="typeId" type="java.lang.Integer">
            <column name="typeId" />
            <generator class="identity" />
        </id> 
         <property name="type" type="java.lang.String">
            <column name="type" length="12" />
        </property>          
    </class>
</hibernate-mapping>

 TbFlower.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping>
    <class name="zhu.po.TbFlower" table="tbflower" catalog="jdbc01">
        <id name="flowerId" type="java.lang.Integer">
            <column name="flowerId" />
            <generator class="identity" />
        </id>
        <property name="typeId" type="java.lang.Integer">
            <column name="typeId" length="12" />
        </property>
         <property name="flower" type="java.lang.String">
            <column name="flower" length="12" />
        </property>              
    </class>
</hibernate-mapping>

 5):dao包

 

IFlowerDao.java 

新增修改删除和以前的操作是一样的,,所以下面并没有修改和删除的操作

package zhu.dao;

import java.util.List;
 
import zhu.po.TbFlower;
import zhu.po.TbFlowerTypeVo;

public interface IFlowerDao {
    /**
     * 方法一
     * 查询所有数据
     * 多表查询
     * @return
     */
 public List<TbFlowerTypeVo>  findAll1();
    
 /**
     * 方法2
     * 查询所有数据
     * 多表查询
     * @return
     */
public List<TbFlowerTypeVo>  findAll2();


 
 /** 
  * 新增
  * @param  
  * @return
  */
 public boolean save(TbFlower t);
}

  FlowerImpl.java

第一种方法:

在查询多表的时候,使用TbFlowerTypeVo即可查询,

使用createQuery()的方法查询

第二种方法:

使用的是左链接( left join)进行的查询(左链接就是以左为主,右边的记录可能为空,右链接就是以右为主左边的可能为空) 、

使用createSQLQuery()的方法查询

注意:createQuery与createSQLQuery两者的区别是:

creatQuery用hql语句进行查询,createSQLQuery可以用sql语句查询

creatQuery用hibernate生成的Bean为对象封装到list返回

createSQLQuery是以对象数组进行存储

所以使用createSQLQuery时想以hibernate生成的bean为对象装入list返回,就笔记麻烦

那么可以使用这样的一个方法可以直接转换为对象的

Query query = session.createSQLQuery(sql).addEntity(XXXXXXX.class);
XXXXXXX 代表以hibernate生成的Bean的对象,也就是数据表映射出的Bean。

如果想更清楚的链接createQuery与createSQLQuery两者的区别 可以去看看这边文章 链接 ,上面的内容也是在那里学到的

package zhu.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import zhu.dao.IFlowerDao;
import zhu.po.TbFlower;
import zhu.po.TbFlowerTypeVo;
@Transactional
@Repository(value="flowerDao")
public class FlowerImpl implements IFlowerDao{
  
    SessionFactory sessionFactory;
    
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
     
    public Session getSession(){
        return getSessionFactory().openSession();
    }
  
    /**使用TbFlowerTypeVo即可查询
     * 方法一:
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<TbFlowerTypeVo> findAll1() {//from Student s inner join  s.classes c
     String hql="select new  zhu.po.TbFlowerTypeVo(u.flowerId,u.flower,p.typeId, p.type) from  TbFlower u , TbType p where u.typeId=p.typeId";
     List<TbFlowerTypeVo> listManyVos=getSession().createQuery(hql).list();
     return listManyVos;
    }
    
    /**左链接
     * 方法二:
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<TbFlowerTypeVo> findAll2() {//from Student s inner join  s.classes c
     String sql="select u.*,p.type from TbFlower u left join TbType p on u.typeId=p.typeId";
     List<Object[]> listobje=getSession().createSQLQuery(sql).list();
     List<TbFlowerTypeVo> VolistMany=new  ArrayList<TbFlowerTypeVo>();
     for (int i = 0; i < listobje.size(); i++) {
         Object[] obj=listobje.get(i); 
         VolistMany.add(new TbFlowerTypeVo((Integer)obj[0],(String)obj[2],(Integer)obj[1],(String)obj[3]));
     }
     for (TbFlowerTypeVo userPowerVo : VolistMany) {
        System.out.println(userPowerVo.getFlower());
    }
     return VolistMany;
    }
   
    @Override
    public boolean save(TbFlower t) {
        boolean b=false;
         try {
            getSession().save(t);
            b=true;
            
        } catch (Exception e) { 
        }
         return b;
    }
 
}

 6):service包

IFlowerDaoService.java

package zhu.service;

import java.util.List;

import zhu.po.TbFlower;
import zhu.po.TbFlowerTypeVo;

public interface IFlowerDaoService {
    /**查询所有数据
     * 多表查询
     * @return
     */
 public List<TbFlowerTypeVo>  findAll1();
    
/**
     * 方法2
     * 查询所有数据
     * 多表查询
     * @return
     */
public List<TbFlowerTypeVo>  findAll2();
 
 /**
  *新增
  */
 public boolean save(TbFlower t);
}

 

FlowerDaoServiceImpl.java

package zhu.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import zhu.dao.IFlowerDao;
import zhu.po.TbFlower;
import zhu.po.TbFlowerTypeVo;
import zhu.service.IFlowerDaoService;

@Service
public class FlowerDaoServiceImpl implements IFlowerDaoService{
    @Resource(name="flowerDao")
    IFlowerDao flowerDao;
    
    @Override
    public List<TbFlowerTypeVo> findAll1() {
        // TODO Auto-generated method stub
        return flowerDao.findAll1();
    }
    @Override
    public List<TbFlowerTypeVo> findAll2() {
        // TODO Auto-generated method stub
        return flowerDao.findAll2();
    }

    @Override
    public boolean save(TbFlower t) {
        // TODO Auto-generated method stub
        return flowerDao.save(t);
    }

}

 7:action包(即web包)

 

MantTableAction.java

注意:

ModelDriven:模型驱动,对所有action的模型对象进行批处理

简单的数ModelDriven,意思是直接把实体类当成页面数据的收集为对象

这篇文章写挺全面的可以去看看  链接

package zhu.action;

import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import zhu.po.TbFlower;
import zhu.po.TbFlowerTypeVo;
import zhu.service.impl.FlowerDaoServiceImpl;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@Controller
public class MantTableAction extends ActionSupport implements ModelDriven<TbFlowerTypeVo> {
    TbFlowerTypeVo tbFlowerTypeVo1;
    
    @Autowired
    FlowerDaoServiceImpl myfServiceImpl;
    @Override
    public TbFlowerTypeVo getModel() {
        tbFlowerTypeVo1=new TbFlowerTypeVo();
        return tbFlowerTypeVo1;
    }
    /**方法1
     * 多表查询所有 
     * @return
     */
    public String findAll1(){
        ActionContext actionContext=ServletActionContext.getContext();
        List<TbFlowerTypeVo> list=myfServiceImpl.findAll1();
        actionContext.put("tb1", list);
        return "find";
    }
    
    /**方法2
     * 多表查询所有 
     * @return
     */
    public String findAll2(){
        ActionContext actionContext=ServletActionContext.getContext();
        List<TbFlowerTypeVo> list=myfServiceImpl.findAll2();
        actionContext.put("tb2", list);
        return "find";
    }
    
    /**
     * 新增
     */
    public String save(){
        System.out.println(tbFlowerTypeVo1.getTypeId());
        TbFlower tbFlower=new TbFlower();
        tbFlower.setFlower(tbFlowerTypeVo1.getFlower());
        tbFlower.setTypeId(tbFlowerTypeVo1.getTypeId());
        if (myfServiceImpl.save(tbFlower)) {
            return "ok";
        }
        return "fail";
    }

}

 

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
 <package name="uu" namespace="/tb" extends="struts-default">
 <action name="MantTableAction" class="zhu.action.MantTableAction">
   <result name="find">/jsp/findAll.jsp</result> 
    <result name="fail">/jsp/fail.jsp</result> 
     <result name="ok" type="redirectAction"> 
     <param name="actionName">MantTableAction</param>
     <param name="method">findAll1</param>
     </result> 
 </action> 
 </package>
</struts>    

 8):jsp

findAll.jsp 

 

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>"> 
    <title>多表查询</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
 
  </head>
  
  <body> 
       <div align="center"> 
        <h3>方法1-----</h3>
        <form action="tb/MantTableAction!findAll1.action" method="post">
         <input  type="submit" value="多表查询数据--方法一"/>
        <table border="1" cellspacing="0">
         <thead>
         <tr>
         <td>Id</td><td>花的名称</td><td>花品种</td> 
         </tr>
         </thead>
         <tbody>
         <c:forEach items="${tb1 }" var="tb2">
         <tr>
          <td>${tb2.flowerId} </td>
          <td>${tb2.flower} </td>
          <td> ${tb2.type} </td> 
         </tr> 
         </c:forEach> 
         </tbody>
        </table>
         </form> 
       </div>
       <hr/>        <div align="center"> 
       <h3>方法2-----</h3>
        <form action="tb/MantTableAction!findAll2.action" method="post">
         <input  type="submit" value="多表查询数据--方法二"/>
        <table border="1" cellspacing="0">
         <thead>
         <tr>
         <td>Id</td><td>花的名称</td><td>花品种</td> 
         </tr>
         </thead>
         <tbody>
         <c:forEach items="${tb2 }" var="tb2">
         <tr>
          <td>${tb2.flowerId} </td>
          <td>${tb2.flower} </td>
          <td> ${tb2.type} </td> 
         </tr> 
         </c:forEach> 
         </tbody>
        </table>
         </form> 
       </div>
       
       <hr/>
        
       <div align="center"> 
       <h3>新增-----</h3>
        <form action="tb/MantTableAction!save.action" method="post">
                 啥花 : <input  type="text" name="flower"/><br/>
                品种 : <select name="typeId">
               <option value="1">A品种</option>
               <option value="2">B品种</option>
           </select>
           <br/>
           <br/>
           <input  type="submit" value="新增"/>
         </form> 
       </div>
  </body>
</html>

 运行效果:

 源码下载链接:http://pan.baidu.com/s/1kUG2I3t 密码:dbpi

posted @ 2017-11-23 15:19  Xiao_野猪  阅读(7082)  评论(0编辑  收藏  举报