1. 程式人生 > >整合 Spring + SpringMVC + MyBatis

整合 Spring + SpringMVC + MyBatis

provide star 實現 per ng- 獲取自增 check fas manage

< 一 > POM 配置文件 ( 如果出現 JAR 包 引入錯誤, 請自行下載 )

<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"
>
    <!-- maven項目的基本信息 -->
    <modelVersion
>4.0.0</modelVersion> <groupId>HWQ</groupId> <artifactId>WebSSM</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>WebSSM Maven Webapp</name> <url>http://maven.apache.org</url> <!--
配置引入JAR包的坐標 --> <dependencies> <!-- WEB 服務器模塊 --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <
dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- 數據庫相關模塊 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> <scope>runtime</scope> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!-- MYBATIS 模塊 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <!-- SPRING 相關模塊 --> <!-- 核心依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!-- DAO 層依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!-- WEB 相關依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!-- 單元測試依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!-- 測試模塊 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> <!-- 配置項目打包信息 --> <build> <finalName>WebSSM</finalName> </build> </project>

< 二 > 數據庫基本配置文件

  jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true
  jdbc.class=com.mysql.jdbc.Driver
  jdbc.user=root
  jdbc.word=920619

< 三 > 配置 Mybatis ( mybatis.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>
    
    <settings>
    
        <!-- 配置使用 JDBC 驅動獲取自增長主鍵 -->
        <setting name="useGeneratedKeys" value="true"/>
        
        <!-- 配置使用列別名替換列名, 默認為TRUE -->
        <setting name="useColumnLabel" value="true"/>
        
        <!-- 配置駝峰命名規則 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        
    </settings>
    
</configuration>

< 四 > DAO 接口

package dao;

import java.util.List;
import java.util.Map;

import model.User;

public interface UserDao {
    
    List<Map<String, Object>> selectAllUser();
    
    Integer insertUser(User user);
    
}

< 五 > DAO 對應的 Mapper 配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper 
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd"
>
<mapper namespace="dao.UserDao">

    <select id="selectAllUser" resultType="model.User">
        SELECT * FROM user
    </select>
    
    <insert id="insertUser" parameterType="model.User"  keyProperty="userId" >
        INSERT INTO user ( user_name, user_sex ) 
        VALUES ( #{userName}, #{userSex} )    
    </insert>
    
</mapper>

< 六 > 整合 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: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/context 
    http://www.springframework.org/schema/context/spring-context-4.1.xsd"
>

    <!-- 加載數據路配置信息 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
    <!-- 配置 C3P0 數據源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="driverClass" value="${jdbc.class}"/>
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.word}"/>
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <property name="autoCommitOnClose" value="false"/>
        <property name="checkoutTimeout" value="1000"/>
        <property name="acquireIncrement" value="2"/>
    </bean> 
    
    <!-- 配置 MYBATIS SQL SESSION 工廠 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis.xml"/>
        <property name="typeAliasesPackage" value="model"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>
    
    <!-- 配置自動掃描的 DAO 包, 被動態實現註入到 IOC 容器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="dao"/>
    </bean>
    
</beans>

< 七 > 測試 SPRING + MYBATIS 的整合

package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import dao.UserDao;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-mybatis.xml"})
public class Test01 {
    
    @Autowired
    private UserDao userDao;
    
    @Test
    public void test() {
        System.out.println(userDao.selectAllUser());
    }
    
}

< 八 > 配置 業務層 事務

<?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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.1.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"
>

    <!-- 配置自動掃描的包 -->
    <context:component-scan base-package="service"></context:component-scan>
    
    <!-- 配置事物管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- 開啟事物註解配置 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    
</beans>

< 九 > service 例子 ( 接口和實現類 )

package service.inter;

import java.util.List;
import java.util.Map;

import model.User;

public interface UserService {
    
    public List<Map<String, Object>> selectAllUser(User user);
    
}
package service.imple;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import dao.UserDao;
import model.User;
import service.inter.UserService;

@Service
public class UserImple implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    @Transactional //標誌為事物
    public List<Map<String, Object>> selectAllUser(User user) {
        userDao.insertUser(user);
//        System.out.println(1 / 0);
        return userDao.selectAllUser();
    }

}

< 十 >測試 SERVICE 配置

package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import model.User;
import service.inter.UserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-mybatis.xml", "classpath:spring-service.xml"})
public class Test02 {
    
    @Autowired
    public UserService userService;
    
    @Test
    public void test(){
        User user = new User();
        user.setUserName("張崇超");
        user.setUserSex(1);
        System.out.println(userService.selectAllUser(user)); 
    }
    
}

< 11 > 配置 SPRING MVC

<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.1.xsd"
>
    
    <!-- 開啟 SPRING 註解模式 -->
    <mvc:annotation-driven/>
    
    <!-- 加入對靜態資源的處理, 將 SPRING MVC 無法處理的請求交還給 SERVLET -->
    <mvc:default-servlet-handler/>
    
    <!-- 配置視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WebPage/"/>
        <property name="suffix" value=".html"></property>
    </bean>
    
    <!-- 自動掃描 WEB 相關的包 -->
    <context:component-scan base-package="controller"/>

</beans>

< 12 > WEB-XML 的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
>
    <!-- 配置 SPRING 監聽器, 啟動服務器時啟動 SPRING IOC 容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mybatis.xml,classpath:spring-service.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 配置 SPRING WEB 請求監聽器 -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-webmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 借助 SPRING 過濾器解決控制器獲取的表單數據亂碼問題 -->
    <filter>
        <filter-name>springUtf8Encoding</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>springUtf8Encoding</filter-name>   
        <url-pattern>/*</url-pattern>   
    </filter-mapping>

</web-app>

< 13 > CONTROLLER 類

package controller;

import java.io.IOException;
import java.io.Writer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import model.User;
import service.inter.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @RequestMapping("/userlist")
    public void getUserList(Writer writer){
        User user = new User();
        user.setUserName("程輝");
        user.setUserSex(1);
        try {
            writer.write(userService.selectAllUser(user).toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}

整合 Spring + SpringMVC + MyBatis