JAVA - ssm(SpringMVC,Spring,Mybatis)整合

web後端開發分爲3層html

表現層 SpringMVC  和瀏覽器交互前端

業務層  Spring框架  業務邏輯java

持久層  MyBatis       和數據庫交互mysql

 

整合能夠用配置文件+註解的方式。web

以Spring爲主整合 SpringMVC 和 MyBatisspring

 

開發環境:sql

系統:windows7 64位數據庫

java:IDEAexpress

數據庫:mysqlapache

數據庫管理器:SQLyog

 

先配一下環境變量。。。以前的筆記裏有寫。

tomcat的下載安裝配置

http://www.javashuo.com/article/p-eeakymjt-ek.html

mysql的下載安裝配置

http://www.javashuo.com/article/p-qngrpxcr-gd.html

 

1.建立數據庫

下載安裝打開SQLyog,新建數據庫鏈接

 

而後輸入信息,通常用默認的就行了,輸入密碼

 

 點擊測試鏈接,彈出success說明鏈接成功

 

點擊鏈接,成功登錄。

 輸入sql語句建立數據庫ssm,在裏面建立新表account

CREATE DATABASE ssm;
USE ssm;
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
money DOUBLE
);

建立後左邊刷新看見新庫,table裏面是建立的表。

 

 

 

2. IDEA新建spring架構的工程

File - new  - Project

 

 

 

 

 

 Maven - 勾選Create from archetype - 選擇maven的webapp (有不少webapp- -別選錯了),上面是選擇JDK版本,貌似如今開發都用8(1.8),我這個是最新的10(也就是1.10)

 

 

 

 填寫組信息,若是建的時候選中了其餘的工程,上面會有parent和add as modeule to的選項,改爲none,否則就變成了其餘工程的下屬module了。

 

 

 

 而後一直next,到最後,這裏找個位置,而後起個項目名字,點finish。

 

 

 

 項目建立完成。

 

3.配置文件:pom.xml

修改properties

    <properties>  <!-- 這裏至關於定義了一些變量,未來修改版本的時候只改這裏就能夠了。 -->
        <spring.version>5.0.2.RELEASE</spring.version>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <shiro.version>1.2.3</shiro.version>
        <mysql.version>5.1.6</mysql.version>
        <mybatis.version>3.4.5</mybatis.version>
    </properties>

修改dependencies

 <dependencies>
    <!-- spring -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.8</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <!-- log end -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>

 

 

 

4.添加必要文件夾

main下面建立2個新文件夾,java 和 resources

 

 

 

把java設爲Sources Root,用來存放java類

 

 

 把resources設爲resources Root, 用來存放js,圖片這類的資源。

 

 

 java下面建立4個package 

controller:用來處理和前臺的交互

dao:持久層或者數據訪問層,用來和數據庫交互

domain:歷來存放javabean(剛接觸的人可能不知道是啥- -其實就是儲存信息的基本類,只有屬性,get,set方法,單純用來儲存數據,這種class類叫作javabean。我是理解爲MVC中M層的entity。。。)

service:用來處理業務邏輯

整個項目的大致結構:web前端 - controller - service - domain - dao - database數據庫

 

 

 

這樣環境就搭建完畢了。

 

 

 

 

 

 

而後嘗試完成目標:對用戶帳戶的操做(添加和查詢)

1.在domain中建立Account類,用來映射剛纔數據庫新建的Account表中的數據。

添加3個屬性對應3個表屬性

package domain;

//CREATE DATABASE ssm;
//USE ssm;
//CREATE TABLE account(
//id INT PRIMARY KEY AUTO_INCREMENT,
//NAME VARCHAR(20),
//money DOUBLE
//);
public class Account {
    private Integer id;
    private String name;
    private double money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }
}

並生成對應get和set方法。

 

2.在dao中建立接口AccountDao,類型是interface。

 

 

 在裏面添加兩個抽象方法,由於AccountDao是接口,因此先不用實現。

package dao;

import domain.Account;

import java.util.List;

public interface AccountDao {
    //返回全部帳戶信息
    public List<Account> findAll();

    //保存全部帳戶信息
    public void saveAccount(Account account);
}

 

3.在service下面建立接口AccountService

package service;

import domain.Account;

import java.util.List;

public interface AccountService {
    //返回全部帳戶信息
    public List<Account> findAll();

    //保存全部帳戶信息
    public void saveAccount(Account account);
}

在service下面建立新文件夾serviceImpl(implement實現),用來實現接口

serviceImpl中添加class類,AccountServiceImpl,先簡單實現兩個方法。

package com.itheima.service.serviceImpl;

import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("accountService")   //表名是實現了哪一個類,讓spring能夠掃描到這個類
public class AccountServiceImpl implements AccountService {
    public List<Account> findAll() {
        System.out.println("業務層查詢全部帳戶");
        return null;
    }

    public void saveAccount(Account account) {
        System.out.println("業務層查詢儲存帳戶");
    }
}

 

在controller下面添加class AccountContoller。

這個類主要負責先後臺交互,後面再具體實現。

 

這樣就完成了account這個對象信息傳遞的 web前端 - controller - service - domain - dao - database數據庫 的基本結構。

 

而後先完成springMVC部分:

1. 添加psringMVC配置文件

在resources中添加spring的配置文件,若是沒有這個選項說明以前pom.xml配置錯了。springframework沒導入

 

 

 而後起個名字springConfig,這個名字不影響,有意義就行,完成後是這個樣子。

 

 

 

java下面建一個package,起個名字叫com.itheima (名字隨意。。。),

而後把目前java下面的4個package放進去。

 

 

 

而後修改springConfig.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:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置spring建立容器時要掃描的包,掃描註解, base-package的值是須要掃描的包名 -->
    <context:component-scan base-package="com.itheima">
        <!--制定掃包規則,不掃描@Controller註解的JAVA類,其餘的仍是要掃描 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan> </beans>

注意包名和剛纔建立的package名字一致。

這裏把controller排除在外,由於這個是spring的配置文件,controller是歸springMVC管。

啓動後spring會把class都實例化。

 

能夠測試一下spring可不能夠用了。

在resources下面添加新配置文件,起名log4j,用來記錄日誌。(dependency中已經配置過了,不加的話會報錯,不過不影響項目運行。由於只是輸出日誌用的。)

 

 在裏面加入配置

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

 

java下面的com.itheima package下面建一個test package,建立類SpringTest用來測試

這裏測試的方法是利用了spring啓動後會掃描java包,而後爲class建立bean對象(名字默認爲class名字,首字母變小寫)。這是實現AOP(面向切面編程,spring的主要思想之一)的必要步驟,因此能夠利用這個來測試spring是否成功建立了對象,從而發現spring是否在工做了。

package com.itheima.test;

import com.itheima.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

    @Test
    public void test1() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("springConfig.xml");//手動加載配置文件
        AccountService as = (AccountService)ac.getBean("accountService");
        as.findAll(); //測試spring可否運行
    }
}

這裏Test是junit裏面的註解(dependency裏面也配置了),專門用於局部測試,添加上後就能夠直接右鍵方法直接運行方法進行測試了。

 

 

 

 

 輸出成功。

說明spring部分沒問題了。

 

 

 

而後開始springMVC

1.配置xml

在resources下面建立Spring Config名字叫:springMVC.xml,用來配置springMVC

 

 

 

 springMVC.xml代碼:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置建立spring容器要掃描的包 -->
    <context:component-scan base-package="com.itheima">
        <!-- 制定掃包規則 ,只掃描使用@Controller註解的JAVA類 -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    <!-- 配置視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean> <mvc:annotation-driven></mvc:annotation-driven>
</beans>

 

修改web.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"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
  <display-name>ssm_web</display-name>
  <!-- 配置spring mvc的核心控制器 -->
  <servlet>
    <servlet-name>springmvcDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置初始化參數,用於讀取springmvc的配置文件,注意名字和springMVC配置文件名字一致 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springMVC.xml</param-value>
    </init-param>
    <!-- 配置servlet的對象的建立時間點:應用加載時建立。取值只能是非0正整數,表示啓動順序 -->
    <load-on-startup>1</load-on-startup>
  </servlet> <servlet-mapping>
  <servlet-name>springmvcDispatcherServlet</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>
  <!-- 配置springMVC編碼過濾器 -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!-- 設置過濾器中的屬性值 -->
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <!-- 啓動過濾器 -->
  <init-param>
    <param-name>forceEncoding</param-name>
    <param-value>true</param-value>
  </init-param> </filter>
  <!-- 過濾全部請求 -->
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

2.修改AccountController

這裏用了String傳值 和ModelAndView傳值 兩種方法

package com.itheima.controller;

import com.itheima.domain.Account;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("account")
public class AccountController {

    @RequestMapping("findAll")
    public ModelAndView findAll(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("findAllAccount");

        Account[] accountList = new Account[2];

        Account a1 = new Account();
        a1.setId(1);
        a1.setMoney(10.0);
        a1.setName("account1");

        Account a2 = new Account();
        a2.setId(2);
        a2.setMoney(20.0);
        a2.setName("account2");

        accountList[0] = a1;
        accountList[1] = a2;
        mav.addObject("accountList", accountList);

        return mav;
    }

    @RequestMapping("saveAccount")
    public String saveAccount(Model model, Account account){

        model.addAttribute("accountName", account.getName());
        return "saveAccount";
    }

}

 

 

3.添加對應jsp頁面

在webapp - WEB-INF下添加pages文件夾,在裏面新建兩個jsp文件,對應兩個方法的返回頁面名字。

 

 

修改index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java"  isELIgnored="false" %>
<html>
<body>
<h2>Hello ssm</h2>
<form action="/account/saveAccount" method="post">
    帳戶信息:<br/>
    帳戶編號:<input type="text" name = 'id'><br/><!--name要和account的屬性一致-->
    帳戶名:<input type="text" name = 'name'><br/>
    金額:<input type="text" name = 'money'><br/>
    <input type ="submit" value = "保存">
</form>
<a href = "/account/findAll">顯示全部帳戶信息</a>
</body>
</html>

 

修改saveAccount.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 10/30/2019
  Time: 7:46 AM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java"  isELIgnored="false" %>
<html>
<head>
    <title>success</title>
</head>
<body>
<div>${accountName} 已保存</div>
</body>
</html>

 

修改findAllAccount.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 10/30/2019
  Time: 7:45 AM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java"  isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table>
    <tr>
        <th>編號</th>
        <th>帳戶名稱</th>
        <th>帳戶金額</th>
    </tr>
<c:forEach items="${accountList}" var="account">
    <tr> <td>${account.id}</td>
        <td>${account.name }</td>
        <td>${account.money }</td>
    </tr>
</c:forEach>
</table>
</body>
</html>

 

啓動tomcat測試一下

 

 點擊保存

 

 返回了index填寫的名字,傳值成功

 

返回index頁面,點擊顯示全部帳戶信息

 

 僞造的數據能夠顯示。

 

springMVC能夠獨立運行。

 

 

 

而後開始整合spring 和 springMVC

修改web.xml

添加監聽器,在tomcat啓動時加載spring的配置

 

 添加的代碼:

  <!-- 配置spring提供的監聽器,用於啓動服務時加載容器 。 該間監聽器只能加載WEB-INF目錄中名稱爲applicationContext.xml的配置文件 -->
  <listener>
    <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class>
  </listener>
  <!-- 由於咱們名字和位置都和默認值不一樣,因此要手動指定spring配置文件位置,注意param-value的值,要和建立的名字一致 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springConfig.xml</param-value>
  </context-param>

修改controller,把手動僞造的數據變爲調用service方法

package com.itheima.controller;

import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("account")
public class AccountController {

    @Autowired   //自動注入,取到spring建立的代理對象,對業務層進行操做。
    private AccountService accountService;

    @RequestMapping("findAll")
    public ModelAndView findAll(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("findAllAccount");

        List<Account> accountList = accountService.findAll();

        mav.addObject("accountList", accountList);

        return mav;
    }

    @RequestMapping("saveAccount")
    public String saveAccount(Model model, Account account){

        model.addAttribute("accountName", account.getName());
        accountService.saveAccount(account);

        return "saveAccount";
    }

}

再運行tomcat,點擊index的按鈕

 

 

調用到了sevice層的方法,整合成功

 

 

開始寫Mybatis部分

1.配置文件

resources下面建立新配置文件

 

名字叫SqlMapConfig.xml 這裏由於是file因此要手動寫後綴名

配置文件代碼:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="pooled"> <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
                <property name="username" value="root"/>       <!--mysql的帳戶密碼,根據本身的mysql實際狀況修改-->
                <property name="password" value="Zy1990526"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--<mapper class="com.itheima.dao.AccountDao"/>--><!--掃描這個class-->
        <package name="com.itheima.dao"/>  <!--掃描包下面全部dao,這樣之後添加新的dao救不用修改了-->
    </mappers>
</configuration>

 

修改AccountDao,經過註解實現操做數據庫

package com.itheima.dao;

import com.itheima.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface AccountDao {

    //返回全部帳戶信息
    @Select("select * from account")   //利用ibatis的註解用sql語句操做數據庫
    public List<Account> findAll();

    //保存全部帳戶信息
    @Insert("insert into account(name,money) values(#{name}, #{money}) ")  //id是自增加的因此只須要name和money的值。
    public void saveAccount(Account account);
}

 

建立測試:

在test下面建立MyBatisTest

package com.itheima.test;

import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class MybatisTest {

    @Test
    public void findAllTest() throws Exception {

        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession session= factory.openSession();
        AccountDao dao = session.getMapper(AccountDao.class);//取得MyBatis生成的代理對象

        List<Account> accountList =  dao.findAll();//調用對象方法,往數據庫裏插入一條數據。
        for(int i=0; i<accountList.size(); i++){
            System.out.println(accountList.get(i).toString());
        }


        session.close();
        in.close();
    }

    @Test
    public void saveAccountTest() throws Exception {
        Account account = new Account();
        account.setId(1);
        account.setName("account1");
        account.setMoney(5000f);
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession session= factory.openSession();
        AccountDao dao = session.getMapper(AccountDao.class);//取得MyBatis生成的代理對象

        dao.saveAccount(account);//調用對象方法,往數據庫裏插入一條數據。

        session.commit(); //提交修改,不然數據庫會回滾。.


        session.close();
        in.close();
    }
}

 

運行saveAccountTest方法後,查看mysql數據庫的account表(aaa和bbb是從數據庫手動插入的,用來測試)

 

運行findAllAccount查詢後(上面的警告是由於JDK版本太高,可能出現不兼容,1.9以上貌似都會有這個警告)

 

 

 

MyBatis獨立運行成功。

 

 

 

開始整合spring和mybatis

1.配置文件

springConfig的beans裏面添加配置,把MyBatis的部分加進來

添加內容後:

<?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:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置spring建立容器時要掃描的包,掃描註解, base-package的值是須要掃描的包名 -->
    <context:component-scan base-package="com.itheima">
        <!--制定掃包規則,不掃描@Controller註解的JAVA類,其餘的仍是要掃描 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>



    <!-- 配置C3P0的鏈接池對象 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/ssm"/>  <!--數據庫名稱-->
        <property name="username" value="root" />           <!--用戶名-->
        <property name="password" value="Zy1990526" />      <!--密碼-->
    </bean>
    <!-- 配置SqlSession的工廠 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 配置掃描dao的包 -->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itheima.dao"/> <!--修改成本身dao的路徑-->
    </bean>

</beans>

而後 SqlMapConfig.xml 就沒用了,把裏面內容清空。

 

 

 

2。修改java部分

修改AccountDao

在上面添加註解@Repository,把接口交給spring掃描

添加後:

package com.itheima.dao;

import com.itheima.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface AccountDao {

    //返回全部帳戶信息
    @Select("select * from account")   //利用ibatis的註解用sql語句操做數據庫
    public List<Account> findAll();

    //保存全部帳戶信息
    @Insert("insert into account(name,money) value(#{name}, #{money}) ")  //id是自增加的。
    public void saveAccount(Account account);
}

 

修改AccountServiceImpl,把裏面的方法與dao的方法掛鉤。

package com.itheima.service.serviceImpl;

import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("accountService")   //表名是實現了哪一個類,讓spring能夠掃描到這個類
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;  //注入dao

    public List<Account> findAll() {
        System.out.println("業務層查詢全部帳戶");
        return accountDao.findAll();
    }

    public void saveAccount(Account account) {
        System.out.println("業務層查詢儲存帳戶");
        accountDao.saveAccount(account);
    }
}

 

這樣整個框架就串起來了

前臺點擊提交後,調用controller,而後controller中使用service中的方法調用dao的方法,dao的方法鏈接數據庫查詢結果後返回結果,給service,service返回給controller,controller傳給跳轉頁面顯示。完成業務流程。

 

整合完成,開始測試

 

 點擊保存

 

頁面跳轉成功,而後返回,點擊顯示全部帳戶信息

 

 成功。

 

ssm框架整合完成。

 

 

而後纔想起來- -id是自增加的,不必在前臺和controller裏面賦值。。。

 

 

 

由於配置文件很容易出問題,並且還很差改,因此把最後完成的完整版的4個配置文件放在這= =

springConfig.xml

變量部分:spring部分的java所在位置。 數據庫信息,整合到spring的dao部分的路徑

com.itheima
<property name="url" value="jdbc:mysql://localhost:3306/ssm"/>  <!--數據庫名稱-->
<property name="username" value="root" /> <!--用戶名-->
<property name="password" value="Zy1990526" /> <!--密碼-->

com.itheima.dao
<?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:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置spring建立容器時要掃描的包,掃描註解, base-package的值是須要掃描的包名 -->
    <context:component-scan base-package="com.itheima">
        <!--制定掃包規則,不掃描@Controller註解的JAVA類,其餘的仍是要掃描 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>



    <!-- 配置C3P0的鏈接池對象 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/ssm"/>  <!--數據庫名稱-->
        <property name="username" value="root" />           <!--用戶名-->
        <property name="password" value="Zy1990526" />      <!--密碼-->
    </bean>
    <!-- 配置SqlSession的工廠 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 配置掃描dao的包 -->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itheima.dao"/> <!--修改成本身dao的路徑-->
    </bean>

</beans>

 

springMVC.xml 

變量部分:springMVC 須要掃的controller所在java包位置,和前端 jsp 頁面所在位置,若是不同須要修改。

com.itheima
/WEB-INF/pages/
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置建立spring容器要掃描的包 -->
    <context:component-scan base-package="com.itheima">
        <!-- 制定掃包規則 ,只掃描使用@Controller註解的JAVA類 -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    <!-- 配置視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

 

web.xml

變量部分: 整合其餘兩個xml用的路徑,若是文件名不同須要修改

classpath:springConfig.xml
classpath:springMVC.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"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
  <display-name>ssm_web</display-name>

  <!-- 配置spring提供的監聽器,用於啓動服務時加載容器 。 該間監聽器只能加載WEB-INF目錄中名稱爲applicationContext.xml的配置文件 -->
  <listener>
    <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class>
  </listener>
  <!-- 由於咱們名字和位置都和默認值不一樣,因此要手動指定spring配置文件位置,注意param-value的值,要和建立的名字一致 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springConfig.xml</param-value>
  </context-param>


  <!-- 配置spring mvc的核心控制器 -->
  <servlet>
    <servlet-name>springmvcDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置初始化參數,用於讀取springmvc的配置文件,注意名字和springMVC配置文件名字一致 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springMVC.xml</param-value>
    </init-param>
    <!-- 配置servlet的對象的建立時間點:應用加載時建立。取值只能是非0正整數,表示啓動順序 -->
    <load-on-startup>1</load-on-startup>
  </servlet> <servlet-mapping>
  <servlet-name>springmvcDispatcherServlet</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>
  <!-- 配置springMVC編碼過濾器 -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!-- 設置過濾器中的屬性值 -->
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <!-- 啓動過濾器 -->
  <init-param>
    <param-name>forceEncoding</param-name>
    <param-value>true</param-value>
  </init-param>
  </filter>
  <!-- 過濾全部請求 -->
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

pom.xml   不用修改

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>SpringMVC_test</groupId>
  <artifactId>ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssm Maven Webapp</name>
  <url>http://www.example.com</url>

  <properties>  <!-- 這裏至關於定義了一些變量,未來修改版本的時候只改這裏就能夠了。 -->
    <spring.version>5.0.2.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <shiro.version>1.2.3</shiro.version>
    <mysql.version>5.1.6</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>

  <dependencies>
    <!-- spring -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.8</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <!-- log end -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>ssm</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

 

注意裏面的變量。。。根據實際狀況修改。

相關文章
相關標籤/搜索