天天看點

SSM整合搭建(三)

SSM整合第三期!!

接着上次的繼續      
上次我們使用逆向工程建立出mapper與bean,然後我們發現 裡面的檔案都有很多注釋, 是以我們可以将它們删除,然後重新生成一遍沒有注釋的      

把之前剛生成的都先删除,就是生成的bean,還有dao中和mapper中的檔案,直接删除。

然後隻需要在mgb.xml中加入一段代碼即可 具體在該網址http://mybatis.org/generator/running/runningWithJava.html

SSM整合搭建(三)
<commentGenerator>
      <property name="suppressAllComments" value="true" />
    </commentGenerator>      

然後我們來重新生成一遍  生成的就是沒有注釋的了 記得生成了要重新整理

SSM整合搭建(三)

這就大概生成了所有的方法啦,到時候我們可以修改一些我們需要用的。

首先我們的EmployeeMapper.xml裡面檔案過多 我們可以進行縮小便于整理

SSM整合搭建(三)

 然後我們發現,少了聯合查詢這個功能,我們隻能自己寫,于是來到EmployeeMapper,新增兩個方法

//新增兩個
    List<Employee> selectByExampleWithDept(EmployeeExample example);

    Employee selectByPrimaryKeyWithDept(Integer empId);      
SSM整合搭建(三)

 然後需要為Employee增加department字段 并且生成get set方法

SSM整合搭建(三)
private Department department;
    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }      

定義好了EmployeeMapper 和 bean 那麼就需要去定義xml的映射sql語句

來到EmployeeMapper.xml  插入

<!--     List<Employee> selectByExampleWithDept(EmployeeExample example);

    Employee selectByPrimaryKeyWithDept(Integer empId);
   -->
   <select id="selectByExampleWithDept" >
           select
        <if test="distinct">
          distinct
        </if>
        <include refid="Base_Column_List" />
        from tbl_emp
        <if test="_parameter != null">
          <include refid="Example_Where_Clause" />
        </if>
        <if test="orderByClause != null">
          order by ${orderByClause}
        </if>
   </select>      

然後再進行修改  之後我們發現那個Base_Column_List 中定義的sql語句并不包含新增加的department,是以我們再沖洗寫一個sql語句

SSM整合搭建(三)
<sql id="WithDept_Column_List">
       emp_id, emp_name, gender, email, d_id,dept_id,dept_name
  </sql>      

然後将原來的Base_Column_List 改成我們新定義的id,然後因為原來的語句是從emp表查詢,而我們需要查出department的屬性,那就肯定需要聯合查詢了。

那我這裡就直接放代碼了

SSM整合搭建(三)
<sql id="WithDept_Column_List">
       e.emp_id, e.emp_name, e.gender, e.email, e.d_id,d.dept_id,d.dept_name
  </sql>      
SSM整合搭建(三)
<!--     List<Employee> selectByExampleWithDept(EmployeeExample example);

    Employee selectByPrimaryKeyWithDept(Integer empId);
   -->
   <select id="selectByExampleWithDept" >
           select
        <if test="distinct">
          distinct
        </if>
        <include refid="WithDept_Column_List" />
        FROM tbl_emp e LEFT JOIN tbl_dept d ON e.`d_id` = d.`dept_id`
        <if test="_parameter != null">
          <include refid="Example_Where_Clause" />
        </if>
        <if test="orderByClause != null">
          order by ${orderByClause}
        </if>
   </select>      

将上述資訊定義好後,還需要定義一個傳回的類型,因為我們使用了别名,就使用resultMap

SSM整合搭建(三)
<resultMap type="com.atguigu.crud.bean.Employee" id="WithDeptResultMap">
      <id column="emp_id" jdbcType="INTEGER" property="empId" />
    <result column="emp_name" jdbcType="VARCHAR" property="empName" />
    <result column="gender" jdbcType="CHAR" property="gender" />
    <result column="email" jdbcType="VARCHAR" property="email" />
    <result column="d_id" jdbcType="INTEGER" property="dId" />
    <association property="department" javaType="com.atguigu.crud.bean.Department">
        <id column="dept_id" property="deptId"/>
        <result column="dept_name" property="deptName"/>
        
    </association>
  </resultMap>      

然後将id傳回之前的select

SSM整合搭建(三)

 然後我們來開始寫第二個方法  根據主鍵查詢  并且将resultMap設為剛才的id 其他的都與上一個一樣

SSM整合搭建(三)
<select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">
      select 
    <include refid="WithDept_Column_List" />
     FROM tbl_emp e LEFT JOIN tbl_dept d ON e.`d_id` = d.`dept_id`
    where emp_id = #{empId,jdbcType=INTEGER}
  </select>      

Mapper搭建完成後,我們開始去測試mapper

SSM整合搭建(三)

 這裡我們直接使用Spring的單元測試,則需要導入Spring單元測試的包

<!-- Spring單元測試 -->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.7.RELEASE</version>
    <!-- <scope>test</scope> -->
</dependency>      

然後使用@ContextConfiguration  代表可以使用Spring測試類并制定Spring配置檔案的位置

SSM整合搭建(三)
SSM整合搭建(三)

 然後加上RunWith 表示使用Spring的單元測試子產品

SSM整合搭建(三)

 然後用autowired 引入我們的Department類

SSM整合搭建(三)

 然後我們進行測試一下結果如下就是成功了

SSM整合搭建(三)

 然後我們要去給department表中插入資料,首先要給department指派,我們建立一個構造方法來友善複制,來到department實體類

SSM整合搭建(三)
private void department() {
        // TODO Auto-generated method stub

    }
    
    public Department(Integer deptId, String deptName) {
        super();
        this.deptId = deptId;
        this.deptName = deptName;
    }      

然後我們開始插入部門資訊  資料庫也成了。

SSM整合搭建(三)
@Test
    public void testCRUD() {
        //1.插入部門
        departmentMapper.insertSelective(new Department(null, "開發部"));
        departmentMapper.insertSelective(new Department(null, "測試部"));

    }      

然後部門插入完畢以後,我們可以插入Employee的具體資訊,為了友善,還是一樣去Employee實體類增加有參構造和無參構造器。 有參構造器先不要department

private void employee() {
        // TODO Auto-generated method stub

    }

    public Employee(Integer empId, String empName, String gender, String email, Integer dId) {
        super();
        this.empId = empId;
        this.empName = empName;
        this.gender = gender;
        this.email = email;
        this.dId = dId;
}      

然後我們再插入使用者資訊試試

SSM整合搭建(三)
@Test
    public void testCRUD() {
        //1.插入部門
//        departmentMapper.insertSelective(new Department(null, "開發部"));
//        departmentMapper.insertSelective(new Department(null, "測試部"));
        
        //測試員工插入
        employeeMapper.insertSelective(new Employee(null, "sasa", "M", "[email protected]", 1));

    }      

運作成功後可以去資料庫裡看看。

然後我們可以進行批量的插入資料。

那麼既然要批量的插入資料,那麼我們就需要傳回applicationContext.xml中去定義可以批量插入的sqlSession了。  其中SqlSessionTemplate 就是跟Spring整合時使用的,更詳細的内容大家可以去看視訊哦

SSM整合搭建(三)
<!-- 配置一個可以執行批量的SqlSession   executorType 執行器類型改為批量-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
        <constructor-arg name="executorType" value="BATCH"></constructor-arg>
    </bean>      

配置好以後就可以在測試頁面注入sqlsession了。

SSM整合搭建(三)

 然後我們來編寫代碼

SSM整合搭建(三)
@Test
    public void testCRUD() {
        //1.插入部門
//        departmentMapper.insertSelective(new Department(null, "開發部"));
//        departmentMapper.insertSelective(new Department(null, "測試部"));
        
        //測試員工插入
        //employeeMapper.insertSelective(new Employee(null, "sasa", "M", "[email protected]", 1));
        
//        for() {
//            employeeMapper.insertSelective(new Employee(null, empName, gender, email, dId))
//        }
        //隻有通過sqlSession來插入才是批量 直接for循環那就不是批量插入了
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        for(int i=0;i<1000;i++) {
            String uid = UUID.randomUUID().toString().substring(0,5)+i;
            mapper.insertSelective(new Employee(null, uid, "M", uid+"@qq.com", 1));
        }
    }      
SSM整合搭建(三)

 然後插入就完成了。

後面就是正式開始做項目了。這裡先理一理流程。

SSM -CRUD  Create(建立)  Retrieve(查詢)  Update(更新)  Delete(删除)
    *功能:1.分頁  2.資料校驗:jquery前端校驗 + JSR303後端校驗  3 ajax  4 Rest風格的URI 使用HTTP協定請求方式的動詞,來辨別對資源的操作
    *技術點:  基礎架構-ssm   資料庫-Mysql  前端架構-bootstrap 快速搭建簡潔美觀的頁面  項目的依賴管理:Maven  分頁 pagehelper 逆向工程

*操作過程:1 搭建maven工程  
    2. 引入項目依賴的jar包 :spring springmvc mybatic 資料庫連接配接池驅動包  其他(jstl servlet-api  junit)
    3.引入bootstrap 前端架構
*編寫ssm整合的關鍵配置檔案
    *web.xml spring  springmvc  mybatis  使用mybatis的逆向工程生成對應的bean以及mapper
    *測試mapper 

*驗證完成後首先做首頁

查詢    URI:/emps
1.通路index.jsp頁面
2.index.jsp頁面發送出查詢員工清單請求
3.EmployeeController來接收請求,查出員工資料
4.來到list.jsp頁面進行展示

查詢通過Ajax
1.index.jsp頁面直接發送ajax請求進行員工分頁資料的查詢
2.伺服器将查出的資料 以json字元串的形式傳回給浏覽器
3.浏覽器收到js字元串 可以使用js對json進行解析 使用js通過dom增删改查改變頁面
4.傳回json 實作用戶端的無關性

*新增  邏輯
    1.在index.jsp頁面點選新增
    2.彈出新增對話框
    3.去資料庫查詢部門清單,顯示在對話框中
    4.使用者輸入資料進行校驗,完成儲存 (重要資料後端校驗:JSR303,唯一限制)
規定URI
 /emp/{id}  GET 查詢員工
/emp POST 儲存員工
/emp/{id} PUT 修改員工
/emp/{id} DELETE 删除員工
 
*修改-邏輯
    1.點選編輯
    2.彈出使用者修改的模态框(顯示使用者資訊)
    3.點選更新,完成使用者修改

*删除-邏輯
1.單個删除
URI:/emp/id      

在成功的測試了Departmentmapper的功能與在EmployeeMapper中插入1000條資料後,我們可以正式的開始寫項目類。首先要完成的是一個分頁的操作,首先我們要進入員工資訊表格的話需要先将員工的資訊全部查找出來放在頁面上,需要一個通道進入controller查找,于是我們将index.jsp改造一下,變成一個跳闆,去到我們的Controller。

SSM整合搭建(三)

 在将index.jsp設定好跳闆後,我們就需要寫一個後續接收的地方(controller)層

SSM整合搭建(三)

 在設定好以後進入,因為這是要接收頁面通過Springmvc的請求,之前在SpringMVC中标注了隻掃描@Controller的包,那麼就給這個class标注@Controller

SSM整合搭建(三)

 标注好後,我們需要寫一個方法來接收之前傳輸來的/emp 請求,建立一個getEmps方法 并标注@RequestMapping(“/emps”)接收頁面傳來的指令

SSM整合搭建(三)

 然後我們要去資料庫中擷取員工的資訊,是以我們要去Service層進行資料庫操作,在service中建立一個EmployeeService

SSM整合搭建(三)

 創好以後先給EmployeeService标注上@Service注解,表示被Spring包掃描,之後需要引用EmployeeMapper來進行引用dao層方法進行資料庫操作

SSM整合搭建(三)

 然後建立一個查詢所有員工的方法。暫時先标注為null

SSM整合搭建(三)

 現在EmployeeService的樣子是這樣的

SSM整合搭建(三)

 然後就回到EmployeeController 在上方引入EmployeeService

SSM整合搭建(三)

 并引入getAll()方法并用一個List接收

SSM整合搭建(三)

 但是由于我們做的是分頁查詢,需要對每一頁進行判别,參數會傳來需要擷取哪一頁的資訊,于是我們需要在getEmps()中寫入可能會傳來的參數并賦給一個值

SSM整合搭建(三)

 再然後我們可以通過分頁的插件對分頁進行處理,需要引入PageHelper插件 來到pom.xml

傳入

<!-- 分頁插件 -->
    <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.0.0</version>
    </dependency>      
SSM整合搭建(三)

 傳入後儲存加載,回到EmployeeController

這時就可以引用傳入的插件了,首先在查詢之前先調用startPage() 傳入頁碼以及每頁需要多少的資料我們規定為5

SSM整合搭建(三)

 然後要注意了,這個分頁查詢的PageHelper的下一行一定是分頁查詢,之後我們通過new一個PageInfo對查詢後的結果進行包裝,隻需要将pageInfo交給頁面就行了

PageInfo(emps,num) 将查詢後的結果傳入 num代表一個頁碼連續顯示幾頁 比如傳入的是第3頁 那麼就從3開始連續顯示num頁。

最後用model接收這個pageinfo,這時要在标題處傳入Model model

SSM整合搭建(三)

 最後将model傳到request請求中

最後的頁面是這樣的:

SSM整合搭建(三)

 好的當我們已經将分頁的步驟基本設計好以後,那麼就先去測試中測試一下。在test包下建立一個MvcTest

SSM整合搭建(三)

 當我們建好以後,還是跟上次一樣通過Spring進行測試那麼先引入注解

@RunWith(SpringJUnit4ClassRunner.class)        和
@ContextConfiguration(locations = {"classpath:applicationContext.xml","file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml"})      

因為這次我們測試用到了Springmvc 是以需要它的配置檔案,我們也順帶一起引入

SSM整合搭建(三)

 引入後因為我們這次要配合SpringMVC一起測試,那麼先傳入SpringMvc的ioc WebApplicationContext,然後虛拟MVC請求并擷取處理結果在這裡我們使用MockMvc(詳細見圖)

SSM整合搭建(三)

 然後我們寫一個初始化MockMvc的方法(可能某些地方解釋的不清楚,以為我也是剛學,還需要各位自己去查啦)

SSM整合搭建(三)

 建立好後呢我們就可以開始寫Test方法,首先先建立一個testPage方法并标注@Test

SSM整合搭建(三)

  然後在方法中設定MvcResult result 用來接收處理的結果,并使用剛初始化的mockMvc執行模拟進入/emps 并傳入參數pn為1的參數傳回

SSM整合搭建(三)

 在擷取之後建立一個MockHttpServletRequest request 擷取結果中的請求資訊。

然後再從請求資訊中擷取pageInfo

SSM整合搭建(三)

 (之前忘了一個在initMockMvc前加上一個@Before注解表示最先執行記住引入的是測試的包)并且在類上方加入@WebAppConfiguration注解表示傳入web ioc容器

SSM整合搭建(三)

 做到這一步後,之後就是從pageInfo中擷取資訊啦,就不一一闡述了直接上圖

SSM整合搭建(三)

 輸出的結果是這樣的  我們的測試也就完成了

SSM整合搭建(三)