黑猴子的家:JavaEE 之 SSM 框架整合

1、整合前需要注意的問題

尖叫提示:框架版本是否兼容
1) 查看不同MyBatis版本整合Spring時使用的適配包
http://www.mybatis.org/spring/

2)下載整合適配包
https://github.com/mybatis/spring/releases

3)官方整合示例怔檩,jpetstore
https://github.com/mybatis/jpetstore-6

2缎讼、SSM整合思想

1)導入整合需要的jar包

(1)Spring的jar包
(2)SpringMVC的jar包
(3)MyBatis的jar包
(4)整合的適配包
(5)數(shù)據(jù)庫驅動包手报、日志包、連接池等

2)MyBatis環(huán)境的搭建

(1)MyBatis的全局配置文件
(2)編寫javaBean员辩,Mapper接口,sql映射文件

3)Spring SpringMVC環(huán)境的搭建

(1)web.xml中配置SpringIOC容器啟動的監(jiān)聽器、SpringMVC的核心控制器痊银、REST過濾器
(2)編寫Spring的配置文件: applicationContext.xml
(3)編寫SpringMVC的配置文件: springmvc.xml

4)Spring整合MyBatis

(1)配置創(chuàng)建SqlSession對象的SqlSessionFactoryBean
(2)配置掃描所有的Mapper接口,批量生成代理實現(xiàn)類施绎,交給Spring管理的溯革,能夠完成自動注入.

5)編碼測試

完成員工的增刪改查.

3、SSM 框架整合實操

1)創(chuàng)建web 工程

(1) File -> New -> Other

(2)Dynamic Web Project -> Next

(3)Project name -> Finish

2)導入jar包


(1)Spring jar 包

com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
commons-logging-1.1.3.jar

(2)Spring MVC jar 包

spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar

(3)MyBatis jar包

mybatis-3.4.1.jar

(4)JSTL jar 包

taglibs-standard-impl-1.2.1.jar
taglibs-standard-spec-1.2.1.jar

(5)整合的適配包

mybatis-spring-1.3.0.jar

(6)驅動谷醉、日志鬓照、連接池包

c3p0-0.9.1.2.jar
log4j.jar
mysql-connector-java-5.1.37-bin.jar

(7)反向工程jar包

mybatis-generator-core-1.3.2.jar

(8)log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
   <param name="Encoding" value="UTF-8" />
   <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n" />
   </layout>
 </appender>
 <logger name="java.sql">
   <level value="debug" />
 </logger>
 <logger name="org.apache.ibatis">
   <level value="info" />
 </logger>
 <root>
   <level value="debug" />
   <appender-ref ref="STDOUT" />
 </root>
</log4j:configuration>

(9)分頁jar包

pagehelper-5.0.0-rc.jar
jsqlparser-0.9.5.jar
3)MyBatis 環(huán)境搭建

思想
MyBatis的全局配置文件
編寫javaBean,Mapper接口孤紧,sql映射文件

方式
使用逆向工程方式實現(xiàn)

(1)添加逆向工程jar包

mybatis-generator-core-1.3.2.jar

(2)添加mbg.xml 配置文件
mbg.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>

  <!-- targetRuntime: 指定生成的逆向工程的版本
            MyBatis3:  生成帶條件的增刪改查.
            MyBatis3Simple:  生成基本的增刪改查.
   -->
  <context id="DB2Tables" targetRuntime="MyBatis3">
  
    <!-- 數(shù)據(jù)庫的連接 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/mybatis"
        userId="root"
        password="root">
    </jdbcConnection>

    <!-- 指定javabean的生成策略 
        targetPackage: 指定包
        targetProject: 指定工程
    -->
    <javaModelGenerator targetPackage="com.alex.ssm.entity" targetProject=".\src">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>
    
    <!-- sql映射的生成策略  -->
    <sqlMapGenerator targetPackage="com.alex.ssm.mapper"  targetProject=".\resources">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>
    
    <!-- mapper接口的生成策略 -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.alex.ssm.mapper"  targetProject=".\src">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

    <!-- 指定逆向分析的表 -->
    <table tableName="tbl_dept" domainObjectName="Department"></table>
    <table tableName="tbl_employee" domainObjectName="Employee"></table>
    
  </context>
</generatorConfiguration>

(3)創(chuàng)建包文件

com.alex.ssm.entity
com.alex.ssm.mapper
com.alex.ssm.test

(4)創(chuàng)建逆向工程方法
MyBatisTestMBG.java

package com.alex.mybatis.test;

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

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class MyBatisTestMBG {

    @Test
    public void createMBG() throws Exception {
           List<String> warnings = new ArrayList<String>();
           boolean overwrite = true;
           File configFile = new File("mbg.xml");
           ConfigurationParser cp = new ConfigurationParser(warnings);
           Configuration config = cp.parseConfiguration(configFile);
           DefaultShellCallback callback = new DefaultShellCallback(overwrite);
           MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
           myBatisGenerator.generate(null);
    } 
}

(5)創(chuàng)建db.properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true
jdbc.username=root
jdbc.password=root

(6)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">
<!-- MyBatis的全局配置文件 -->
<configuration>

    <!-- properties: 
            引入外部化的配置文件
            resource: 加載類路徑下的資源文件
            url: 加載網(wǎng)絡路徑或者是磁盤路徑下的資源文件
    -->
    <properties resource="db.properties" ></properties>
    
    <!-- settings:
            包含很多重要的設置項豺裆,可以改變MyBatis框架的運行行為
            setting:具體的一個設置項
                name: 設置項的名稱
                value:設置項的取值
    -->
    <settings>
        <!-- 映射下劃線到駝峰命名    last_name ==> lastName    -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- 開啟延遲加載 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 指定加載的屬性是按需加載. -->
        <setting name="aggressiveLazyLoading" value="false"/>
        <!-- 二級緩存 -->
        <setting name="cacheEnabled" value="true"/>
    </settings>
    
    <!-- typeAliases
            別名處理,給java類型取別名(簡短)
            typeAlias:給單個的java類型取別名
                type:指定java類型(全類名)
               alias:指定別名号显。默認的別名是類名的首字母小寫. 別名不區(qū)分大小寫.
             package:批量取別名臭猜,給指定的包下的所有的類取默認的別名
                name:指定包名
     -->
    <typeAliases>
        <!-- <typeAlias type="com.alex.ssm.entity.Employee" alias="employee"/> -->
        <package name="com.alex.ssm.entity"/>
    </typeAliases>
    
    <!-- environments: 環(huán)境們。 支持配置多個環(huán)境. 通過default來指定具體使用的環(huán)境.
            environment: 具體的一個環(huán)境配置押蚤,必須包含transactionManager蔑歌,dataSource。
                id: 當前環(huán)境的唯一標識.
                transactionManager: 事務管理器.
                    JDBC: JdbcTransactionFactory
                            將來事務管理會交給Spring的聲明式事務.@Trancation
                dataSource:數(shù)據(jù)源.
                    POOLED: PooledDataSourceFactory
                                將來數(shù)據(jù)源交給Spring管理,使用c3p0或者dbcp等
    -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
        
        <environment id="test">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    
    <!-- 
        mappers:引入sql映射文件
            mapper:引入單個的sql映射文件
            package: 批量引入sql映射文件    
            要求: sql映射文件的名字與Mapper接口的名字一致.并且在同一目錄下.
    -->
    <mappers>
        <!-- <mapper resource="EmployeeMapper.xml"  /> -->
        <package name="com.alex.ssm.mapper"/>
    </mappers>
    
</configuration>

(7)mybatis.sql

/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50515
Source Host           : localhost:3306
Source Database       : mybatis

Target Server Type    : MYSQL
Target Server Version : 50515
File Encoding         : 65001

Date: 2019-10-16 14:38:06
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for tbl_dept
-- ----------------------------
DROP TABLE IF EXISTS `tbl_dept`;
CREATE TABLE `tbl_dept` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `department_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tbl_dept
-- ----------------------------
INSERT INTO `tbl_dept` VALUES ('1', '開發(fā)部');
INSERT INTO `tbl_dept` VALUES ('2', '測試部');
INSERT INTO `tbl_dept` VALUES ('3', '財務部');
INSERT INTO `tbl_dept` VALUES ('4', '人事部');

-- ----------------------------
-- Table structure for tbl_employee
-- ----------------------------
DROP TABLE IF EXISTS `tbl_employee`;
CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `last_name` varchar(50) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `gender` char(1) DEFAULT NULL,
  `d_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_emp_dept` (`d_id`),
  CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1006 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tbl_employee
-- ----------------------------
INSERT INTO `tbl_employee` VALUES ('1001', 'Tom', 'Tom@aliyun.com', '1', '1');
INSERT INTO `tbl_employee` VALUES ('1002', 'Rose', 'rose@aliyun.com', '0', '2');
INSERT INTO `tbl_employee` VALUES ('1003', 'Alex', 'alex@qq.com', '1', '3');
INSERT INTO `tbl_employee` VALUES ('1004', 'Thone', 'Thone@aliyun.com', '0', '4');
INSERT INTO `tbl_employee` VALUES ('1005', 'Jerry', 'jerry@aliyun.com', '1', '2');

(8)創(chuàng)建Mybatis測試方法

package com.alex.mybatis.test;

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

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 com.alex.ssm.entity.Employee;
import com.alex.ssm.entity.EmployeeExample;
import com.alex.ssm.entity.EmployeeExample.Criteria;
import com.alex.ssm.mapper.EmployeeMapper;

public class MyBatisTestMBG {

    public SqlSessionFactory getSqlSessionFactory() throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        System.out.println(sqlSessionFactory);
        return sqlSessionFactory;
    }

    // 根據(jù)id查詢
    @Test
    public void testMBG01() throws Exception {
        SqlSessionFactory ssf = getSqlSessionFactory();
        SqlSession session = ssf.openSession();
        try {
            EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
            Employee employee = mapper.selectByPrimaryKey(1001);
            System.out.println(employee);
        } finally {
            session.close();
        }
    }

    // 沒有條件的情況揽碘,查詢全部信息
    @Test
    public void testMBG02() throws Exception {
        SqlSessionFactory ssf = getSqlSessionFactory();
        SqlSession session = ssf.openSession();
        try {
            EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
            List<Employee> emps = mapper.selectByExample(null);
            for (Employee employee : emps) {
                System.out.println(employee);
            }
        } finally {
            session.close();
        }
    }

    // 按照條件查詢
    @Test
    public void testMBG03() throws Exception {
        SqlSessionFactory ssf = getSqlSessionFactory();
        SqlSession session = ssf.openSession();
        try {
            EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);

            // 查詢員工名字中帶有e字母 和員工性別是2的 或者email中帶有y字母的
            EmployeeExample example = new EmployeeExample();

            Criteria criteria = example.createCriteria();
            criteria.andLastNameLike("%e%");
            criteria.andGenderEqualTo("0");

            // or的條件需要重新使用一個Criteria對象
            Criteria criteria2 = example.createCriteria();
            criteria2.andEmailLike("%y%");

            // 對于封裝or條件的criteria次屠,需要or到example
            example.or(criteria2);
            List<Employee> emps = mapper.selectByExample(example);
            for (Employee employee : emps) {
                System.out.println(employee);
            }
        } finally {
            session.close();
        }
    }
}
4)Spring SpringMVC 環(huán)境的搭建

(1)思想
web.xml中配置
SpringIOC容器啟動的監(jiān)聽器
SpringMVC的核心控制器
REST過濾器
UTF-8編碼
編寫Spring的配置文件: applicationContext.xml
編寫SpringMVC的配置文件: springmvc.xml

(2)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" id="WebApp_ID" version="2.5">
  <display-name>ssm</display-name>
  
    <!-- 實例化SpringIOC容器的監(jiān)聽器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- 配置utf-8編碼 -->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- REST 過濾器 -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    
    <!-- Springmvc的核心控制器 -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
</web-app>

(3)spring-context.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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.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.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- 開啟注解掃描 -->
    <context:component-scan base-package="com.alex.ssm">
        <!-- Springmvc管理的,Spring就不管理 -->
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- 讀取外部文件 -->
    <context:property-placeholder location="classpath:/db.properties" />

    <!-- C3P0 數(shù)據(jù)源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
        <property name="minPoolSize" value="${jdbc.minPoolSize}" />
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
        <property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
        <property name="maxStatements" value="${jdbc.maxStatements}" />
        <property name="maxStatementsPerConnection" value="${jdbc.maxStatementsPerConnection}" />
    </bean>

    <!-- 事務切面 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 開啟基于注解的聲明式事務 transaction-manager="transactionManager" 默認值,可以省略. -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

(4)springmvc-context.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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.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.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
        
    <!-- 注解掃描 -->
    <context:component-scan base-package="com.alex.ssm" use-default-filters="false">
        <!-- 只掃描SpringMVC相關的組件 -->
        <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/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
   <mvc:default-servlet-handler/>
   <mvc:annotation-driven/>
    
</beans>

(5)db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true
jdbc.username=root
jdbc.password=root
jdbc.initialPoolSize=30
jdbc.minPoolSize=10
jdbc.maxPoolSize=100
jdbc.acquireIncrement=5
jdbc.maxStatements=1000
jdbc.maxStatementsPerConnection=10
5)Spring整合MyBatis

配置創(chuàng)建SqlSession對象的SqlSessionFactoryBean
配置掃描所有的Mapper接口雳刺,批量生成代理實現(xiàn)類劫灶,交給Spring管理的,能夠完成自動注入.

(1)spring-context.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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.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.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- 開啟注解掃描 -->
    <context:component-scan base-package="com.alex.ssm">
        <!-- Springmvc管理的掖桦,Spring就不管理 -->
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- 讀取外部文件 -->
    <context:property-placeholder location="classpath:/db.properties" />

    <!-- C3P0 數(shù)據(jù)源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
        <property name="minPoolSize" value="${jdbc.minPoolSize}" />
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
        <property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
        <property name="maxStatements" value="${jdbc.maxStatements}" />
        <property name="maxStatementsPerConnection" value="${jdbc.maxStatementsPerConnection}" />
    </bean>

    <!-- 事務切面 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 開啟基于注解的聲明式事務 transaction-manager="transactionManager" 默認值,可以省略. -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    
    <!-- 整合 MyBatis MyBatis的配置都可以在Spring里面配置本昏,但是盡量把MyBatis獨有的還是放在MyBatis配置文件里-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入數(shù)據(jù)源 -->
        <property name="dataSource" ref="dataSource" ></property>
        <!-- 指定MyBatis的全局配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!-- 指定sql映射文件 -->
        <property name="mapperLocations" value="classpath:com/alex/ssm/mapper/*.xml"></property>
    </bean>
    
    <!-- 掃描所有mapper接口,批量生成代理實現(xiàn)類枪汪,交給Spring容器來管理 -->
    <!-- 這是老版本的配置方式涌穆,沒辦法指定ID,ID默認是類的首字母小寫 -->
    <!-- 
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.alex.ssm.mapper"></property>
    </bean>
    -->
    
    <!-- 掃描所有mapper接口怔昨,批量生成代理實現(xiàn)類,交給Spring容器來管理 -->
    <!-- 新方式 宿稀, 兩種方式趁舀,使用哪一種都可以-->
    <mybatis-spring:scan base-package="com.alex.ssm.mapper"/>
</beans>

(2)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">
<!-- MyBatis的全局配置文件 -->
<configuration> 
   
    <settings>
        <!-- 映射下劃線到駝峰命名    last_name ==> lastName    -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- 開啟延遲加載 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 指定加載的屬性是按需加載. -->
        <setting name="aggressiveLazyLoading" value="false"/>
        <!-- 二級緩存 -->
        <setting name="cacheEnabled" value="true"/>
    </settings> 
     
    <typeAliases>
        <package name="com.alex.ssm.entity"/>
    </typeAliases> 
     
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
    
</configuration>

尖叫提示:把交給Spring 管理的從MyBatis配置文件中刪掉

6)編碼測試

完成員工的增刪改查.
(1)EmployeeController.java

package com.alex.ssm.controller;

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

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

import com.alex.ssm.entity.Employee;
import com.alex.ssm.service.EmployeeService;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService ;
    
    @RequestMapping(value="/emps",method=RequestMethod.GET)
    public String listEmps(Map<String,Object> map) {
        List<Employee> emps = employeeService.getAllEmps();
        map.put("emps",emps);
        return "list";
    }
}

(2)EmployeeService.java

package com.alex.ssm.service;

import java.util.List;

import com.alex.ssm.entity.Employee;

public interface EmployeeService {

    public List<Employee> getAllEmps();
}

(3)EmployeeServiceImpl.Java

package com.alex.ssm.serviceimpl;

import java.util.List;

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

import com.alex.ssm.entity.Employee;
import com.alex.ssm.mapper.EmployeeMapper;
import com.alex.ssm.service.EmployeeService;

@Service
public class EmployeeServiceImpl implements EmployeeService{
    
    @Autowired
    private EmployeeMapper employeeMapper ;

    @Override
    public List<Employee> getAllEmps() {
        List<Employee> example = employeeMapper.selectByExample(null);
        return example;
    }
}

(4)index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <a href="${pageContext.request.contextPath}/emps">List ALL Emps</a>
</body>
</html>

(5)list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- 導入JSTL標簽庫 -->
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1 align="center" >員工信息列表</h1>
    <table border="1px" width="70%" cellspacing="0px" align="center">
        <tr>
            <th>ID</th>
            <th>LastName</th>
            <th>Email</th>
            <th>Gender</th>
            <!-- <th>DeptName</th> -->
            <th>Operation</th>
        </tr>
        <!-- items:指定要迭代的集合   var:代表當前迭代出的對象-->   
        <c:forEach items="${requestScope.emps }" var="emp">
            <tr align="center">
                <td>${emp.id }</td>
                <td>${emp.lastName }</td>
                <td>${emp.email }</td>
                <td>${emp.gender==0?'女':'男' }</td>
                <%-- <td>${emp.dept.departmentName}</td> --%>
                <td>
                    <a href="#">Edit</a>
                    &nbsp;&nbsp;
                    <a href="#">Delete</a>
                </td>
            </tr>
        </c:forEach>
    
    </table>
</body>
</html>
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市祝沸,隨后出現(xiàn)的幾起案子赫编,更是在濱河造成了極大的恐慌,老刑警劉巖奋隶,帶你破解...
    沈念sama閱讀 211,290評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件擂送,死亡現(xiàn)場離奇詭異,居然都是意外死亡唯欣,警方通過查閱死者的電腦和手機嘹吨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評論 2 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來境氢,“玉大人蟀拷,你說我怎么就攤上這事∑剂模” “怎么了问芬?”我有些...
    開封第一講書人閱讀 156,872評論 0 347
  • 文/不壞的土叔 我叫張陵,是天一觀的道長寿桨。 經(jīng)常有香客問我此衅,道長,這世上最難降的妖魔是什么亭螟? 我笑而不...
    開封第一講書人閱讀 56,415評論 1 283
  • 正文 為了忘掉前任挡鞍,我火速辦了婚禮,結果婚禮上预烙,老公的妹妹穿的比我還像新娘墨微。我一直安慰自己,他們只是感情好扁掸,可當我...
    茶點故事閱讀 65,453評論 6 385
  • 文/花漫 我一把揭開白布翘县。 她就那樣靜靜地躺著,像睡著了一般谴分。 火紅的嫁衣襯著肌膚如雪锈麸。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,784評論 1 290
  • 那天狸剃,我揣著相機與錄音掐隐,去河邊找鬼。 笑死钞馁,一個胖子當著我的面吹牛虑省,可吹牛的內容都是我干的。 我是一名探鬼主播僧凰,決...
    沈念sama閱讀 38,927評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼探颈,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了训措?” 一聲冷哼從身側響起伪节,我...
    開封第一講書人閱讀 37,691評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎绩鸣,沒想到半個月后怀大,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,137評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡呀闻,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,472評論 2 326
  • 正文 我和宋清朗相戀三年化借,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片捡多。...
    茶點故事閱讀 38,622評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡蓖康,死狀恐怖,靈堂內的尸體忽然破棺而出垒手,到底是詐尸還是另有隱情蒜焊,我是刑警寧澤,帶...
    沈念sama閱讀 34,289評論 4 329
  • 正文 年R本政府宣布科贬,位于F島的核電站泳梆,受9級特大地震影響,放射性物質發(fā)生泄漏榜掌。R本人自食惡果不足惜鸭丛,卻給世界環(huán)境...
    茶點故事閱讀 39,887評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望唐责。 院中可真熱鬧鳞溉,春花似錦、人聲如沸鼠哥。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至于颖,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背冒晰。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評論 1 265
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留壶运,地道東北人浪秘。 一個月前我還...
    沈念sama閱讀 46,316評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像耸携,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子夺衍,可洞房花燭夜當晚...
    茶點故事閱讀 43,490評論 2 348

推薦閱讀更多精彩內容