1. 程式人生 > >整合Spring+SpringMVC+Mybatis+Maven+Mysql

整合Spring+SpringMVC+Mybatis+Maven+Mysql

Spring+SpringMVC+Mybatis+Maven+Mysql

一、建立Maven專案

建立完成此時的包結構目錄:

這裡寫圖片描述

此時在WEB-INF下已經有一個log4j.xml配置檔案,檢視此檔案內容可以看到已經自動對log4j進行了一些基本配置。不過這裡我們採用log4j.properties方式來配置log4j。log4j相關用法參考另一篇部落格:log4j的知識點以及相關報錯問題解決辦法

本專案的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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <packaging>war</packaging> <name>MistraRSSSMMM</name> <groupId>
com.sm</groupId> <artifactId>MistraRSSSMMM</artifactId> <version>1.0-SNAPSHOT</version> <properties> <file.encoding>UTF-8</file.encoding> <spring.version>3.2.0.RELEASE</spring.version> <mysql.version>5.1.29</mysql.version
>
<servlet.version>3.0-alpha-1</servlet.version> <aspectj.version>1.8.1</aspectj.version> <commons-codec.version>1.9</commons-codec.version> <commons-dbcp.version>1.4</commons-dbcp.version> <jetty.version>8.1.8.v20121106</jetty.version> <slf4j.version>1.7.5</slf4j.version> <testng.version>6.8.7</testng.version> </properties> <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat6-maven-plugin</artifactId> <version>2.1</version> <configuration> <url>http://localhost:8080/manager</url> <server>Tomcat6</server> <port>8080</port> <path>/mistrasssmmm</path> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.17</version> <configuration> <parallel>methods</parallel> <threadCount>10</threadCount> </configuration> </plugin> <!-- mybatisn逆向工程外掛 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <!--配置檔案的位置--> <configurationFile>src/main/resources/generatorConfig.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <executions> <execution> <id>Generate MyBatis Artifacts</id> <goals> <goal>generate</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> </dependency> </dependencies> </plugin> </plugins> </build> <dependencies> <!-- 依賴的spring 類庫--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</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-jdbc</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-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <!-- mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- mybatis核心 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.apache.ibatis</groupId> <artifactId>ibatis-sqlmap</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>org.apache.ibatis</groupId> <artifactId>ibatis-core</artifactId> <version>3.0</version> </dependency> <!--依賴的連線池類庫--> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!--依賴的資料庫驅動類--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!--log4j--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!--jstl--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectj.version}</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.11</version> </dependency> <!--依賴的測試類庫--> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>${testng.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>2.5</version> </dependency> </dependencies> </project>

各個包的版本真的很重要,有時候一個包版本不匹配就會報些奇怪的錯誤,要是想使用不同版本的包就只能自己慢慢調了。

建立好相應的包結構:

這裡寫圖片描述

建立資料庫:建立一張有:使用者名稱、密碼欄位的user表就好了。

二、整合

1、在src/main/resources下建立jdbc.properties和log4j.properties

jdbc.properties

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/ssmintroduction?useUnicode=true&characterEncoding=utf8
db.username=root
db.password=123456

log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG,out

# Console output...
log4j.appender.out=org.apache.log4j.ConsoleAppender
log4j.appender.out.layout=org.apache.log4j.PatternLayout
log4j.appender.out.layout.ConversionPattern=%d{HH:mm:ss} %-5p [%F\:%L] -- %m%n
log4j.logger.org.apache=INFO

2、在src/main/resources下建立generatorConfig.xml

在pom.xml裡面已經加入了mybatis-generator-maven-plugin外掛。運用Mybatis逆向工程生成對映類mapper.java、po、mapper.xml檔案到對應的包。相關部落格:Mybatis逆向工程Generator。這裡踩了坑。在maven裡面使用這個外掛有個痛點就是每次啟動Tomcat的時候這個外掛都會執行一次,生成相應的檔案。po類等檔案都能覆蓋掉,但是不會覆蓋*.xml檔案。相當於把裡面的程式碼copy了一次追加在後面。

這裡寫圖片描述

這時候啟動就會報錯:java.lang.IllegalArgumentException: Result Maps collection already contains value for com.sm.mapper.UserMapper.BaseResultMap
網上有相關部落格和解決辦法:
mybatis-generator重新生成程式碼時的SQL對映檔案覆蓋
Mybatis code generator1.3.4版本 XML 檔案重新生成不會覆蓋原檔案
我這裡是建立好依賴,寫好配置檔案generatorConfig.xml之後,在Maven-Projects裡面手動執行了一次mybatis-generator:generate,生成相應檔案之後我就把pom.xml裡面的gengerator依賴註釋掉了。相當於就用一次,這裡寫demo倒是無關緊要。推薦還是自己寫個逆向工程的工具專案,這樣有需要就跑一次,copy過來就好了。

generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>

    <!-- 指定資料庫連線驅動地址 -->
    <classPathEntry location="D:\jarPackage\mysqlforjdbc\mysql-connector-java-5.1.7-bin.jar" />

    <!-- 一個數據庫一個 context -->
    <context id="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 將不會向任何生成的元素添加註釋 -->
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value ="true"/>
        </commentGenerator>
        <!--資料庫連線的資訊:驅動類、連線地址、使用者名稱、密碼 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/ssmintroduction" userId="root" password="123456">
        </jdbcConnection>

        <!-- 預設false,把JDBC DECIMAL 和 NUMERIC 型別解析為 Integer,為 true時把JDBC DECIMAL 和
            NUMERIC 型別解析為java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成PO類的位置 -->
        <javaModelGenerator targetPackage="com.sm.po" targetProject="src/main/java">
            <!-- enableSubPackages:是否讓schema作為包的字尾 -->
            <property name="enableSubPackages" value="false" />
            <!-- 從資料庫返回的值被清理前後的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper.xml對映檔案生成的位置 -->
        <sqlMapGenerator targetPackage="com.sm.mapper" targetProject="src/main/resources">
            <!-- enableSubPackages:是否讓schema作為包的字尾 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper介面生成的位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.sm.mapper" targetProject="src/main/java">
            <!-- enableSubPackages:是否讓schema作為包的字尾 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- 指定資料庫表 -->
        <table tableName="user" domainObjectName="User"></table>

        <!-- 有些表的欄位需要指定java型別
         <table schema="" tableName="">
            <columnOverride column="" javaType="" />
        </table> -->
    </context>
</generatorConfiguration>

這裡有個坑爹的地方就是要自己指定本地的資料庫連線驅動jar包,配置中的< classPathEntry / >標籤。
上面配置的輸出檔案的位置很重要,mapper.xml一定要輸出在resources下面,並且包結構要和UserMapper.java所在包結構一樣。
雙擊:

這裡寫圖片描述

就會發現指定包下已經生成了User.java等檔案:

這裡寫圖片描述

3、開發controller、service、serviceImpl

UserService.java

package com.sm.service;

import com.sm.po.User;

/**
 * Created by Mistra.WR on 2017/11/10/010.
 */
public interface UserService {
    int insertSelective(User user);
}

UserServiceImpl.java

package com.sm.serviceimpl;

import com.sm.mapper.UserMapper;
import com.sm.po.User;
import com.sm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Mistra.WR on 2017/11/10/010.
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapperDao;

    public int insertSelective(User user) {
        return userMapperDao.insertSelective(user);
    }
}

UserAddController.java

package com.sm.controller;

import com.sm.po.User;
import com.sm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by Mistra.WR on 2017/11/10/010.
 */
@Controller
@RequestMapping("/userAdd")
public class UserAddController {
    @Autowired
    private UserService userService;

    @RequestMapping("/index.do")
    public String addPage(){
        return "addUser";
    }

    @RequestMapping("/userAdd.do")
    public String UserAdd(User user, Model model){
        if(userService.insertSelective(user)>0){
            model.addAttribute("successMsg", "註冊成功!");
            model.addAttribute("name", user.getUsername());
            return "success";//返回的頁面
        }else{
            model.addAttribute("failMsg", "註冊失敗!");
            return "fail";
        }
    }
}

4、在src/main/resources下建立mybatis的配置檔案mybatis-config.xml

這個配置檔案相當於用來給實體類定義別名。

mybatis-config.xml

<?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>
    <typeAliases>
        <typeAlias alias="user" type="com.sm.po.User"/>
    </typeAliases>
</configuration>

5、在src/main/resources下建立spring-mybatis.xml

spring和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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd">

    <!--引入屬性檔案-->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <!-- 配置資料來源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${db.driver}" />
        <property name="url" value="${db.url}" />
        <property name="username" value="${db.username}" />
        <property name="password" value="${db.password}" />
    </bean>

    <!-- myBatis檔案 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描entity目錄, 省掉Configuration.xml裡的手工配置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <property name="mapperLocations" value="classpath*:com/sm/mapper/*.xml" />
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage"  value="com.sm.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
    <!-- 配置事務管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置事物的註解方式注入 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="sqlSession"     class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
        <constructor-arg index="1" value="BATCH" />
    </bean>
</beans>

6、在src/main/resources下建立spring-mvc.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    ">
    <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven />
    <!-- 掃描serviceimpl -->
    <context:component-scan base-package="com.sm.serviceimpl" />
    <!-- 為controller加上自動代理 -->
    <aop:aspectj-autoproxy proxy-target-class="true" />
    <!-- controller包(自動注入) -->
    <context:component-scan base-package="com.sm.controller" />

    <!-- **********開啟註解***********
    spring3.1之前DefaultAnnotionHandlerMapping AnnotionMethodHandlerAdapter
    spring3.1之後RequestMappingHandlerMapping RequestMappingHandlerAdapter -->
    <!-- 啟動Spring MVC 的註解功能,完成請求和註解POJO的對映 即啟用@RequestMapping -->
    <bean
            class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" />
            </list>
        </property>
    </bean>
    <bean id="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    </bean>

    <!-- 檢視解析器對模型檢視名稱的解析,即在模型檢視名稱新增前後綴 -->
    <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
        <property name="order" value="10"/>
    </bean>
</beans>

5、配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <!-- Spring-mybatis的配置檔案 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-mybatis.xml</param-value>
  </context-param>
  <!-- log4j的配置檔案 -->
  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
  </context-param>
  <listener>
    <description>spring監聽器</description>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <description>log4j監聽器</description>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
  <!-- 防止spring記憶體溢位監聽器 -->
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>

  <!-- spring mvc servlet -->
  <servlet>
    <description>spring mvc servlet</description>
    <servlet-name>springMvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <description>spring mvc 配置檔案</description>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  <filter>
    <description>字符集過濾器</description&