java SSM框架整合實(shí)戰(zhàn)

這次的ssm整合比較詳細(xì)忽洛,會從單獨(dú)的mybatis連接數(shù)據(jù)庫開始型檀,基本會分為以下幾個(gè)步驟:

1.單獨(dú)使用mybatis

2.Mybatis整合spring - 有Mapper實(shí)現(xiàn)類

3.Mybatis整合spring – 沒有Mapper實(shí)現(xiàn)類

4.Mybatis整合spring – mapper接口掃描

5.Mybatis 整合spring – 整合jdbc事務(wù)

6.整合springmvc

首先,對ssm整合有個(gè)大體的認(rèn)識:

表現(xiàn)層:SpringMVC

包:SpringMVC的jar
配置文件:spring-mvc.xml

業(yè)務(wù)層:Spring

包:spring-ioc Spring-aop Spring-tx Spring-test
配置文件:applicationContext.xml
添加關(guān)于mybatis的配置

持久層:mybatis

包:mybatis自身核心包 Mysql數(shù)據(jù)庫驅(qū)動(dòng)包 C3p0連接池 Mybatis-spring的包
配置文件:sqlMapConfig.xml userMapperxml

一、單獨(dú)使用mybatis

1.導(dǎo)入必須的包:
a)Mybatis自身核心jar:mybatis-3.4.4.jar
b)Log4j日志jar:log4j-1.2.17.jar
c)Oracle驅(qū)動(dòng)jar:odbc14-10.2.0.4.0.jar
maven添加依賴jar包

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.4</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
            <version>10.2.0.4.0</version>
        </dependency>

注意:ojdbc因?yàn)榘鏅?quán)關(guān)系在maven遠(yuǎn)程倉庫中只有目錄沒有jar包的题翻,如果添加配置報(bào)錯(cuò)要手動(dòng)下載相應(yīng)jar包放在本地倉庫的相應(yīng)文件夾就好啦膀藐。

2.建立測試數(shù)據(jù)庫表

create table da_user
(
user_id NUMBER,
user_name VARCHAR2(10),
sex Integer,
JOB VARCHAR2(64),
tel varchar2(32),
email varchar2(64),
hobby varchar2(64)
);

3.建立實(shí)體類
也可以直接用HashMap映射 對于比較簡單的查詢我比較習(xí)慣用這個(gè)
4.建立mapper接口UserMapper:

package com.ways.app.dao;

import java.util.Map;

public interface UserMapper {

    public void saveUser(Map<String,Object> paramsMap); 
}

5.建立sql映射文件userMapper.xml

<?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="com.ways.app.dao.UserMapper">
    <insert id="saveUser" parameterType="java.util.HashMap">
        insert into da_user 
        values (decode((select max(user_id) from da_user),null,1,(select max(user_id) + 1 from da_user)),
                ‘${userName}’,${sex},'${job}','${tel}','${email}','${hobby}')
    </insert>
</mapper>

6.建立sqlMapConfig.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>  
    <!-- 和spring整合后 environments配置將廢除-->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事務(wù)管理 -->
            <transactionManager type="JDBC"/>
            <!-- 數(shù)據(jù)庫連接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.OracleDriver"/>
                <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:XE"/>
                <property name="username" value="zhaohy"/>
                <property name="password" value="oracle"/>
            </dataSource>
        </environment>
    </environments> 
    
    <!-- 查找sql映射文件 -->
    <mappers>
        <mapper resource="com/ways/app/sqlmap/oracle/userMapper.xml"/>
    </mappers>
</configuration>

7.編寫測試類

package ssmTest;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

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.ways.app.dao.UserMapper;

public class MybatisTest {
    @Test
    public void test() throws IOException {
        //1.創(chuàng)建SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        // 加載sqlMapConfig.xml文件
        InputStream ins = Resources.getResourceAsStream("sqlMapConfig.xml");
        
        
        //2.創(chuàng)建SqlSessionFactory
        SqlSessionFactory factory = builder.build(ins);
        
        //3.打開SqlSession
        SqlSession sqlSession = factory.openSession();
        
        //4.獲取mapper接口的對象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        
        //操作
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("userName", "zhaohy");
        paramsMap.put("sex", 1);
        paramsMap.put("job", "java軟件工程師");
        paramsMap.put("tel", "189xxxx0598");
        paramsMap.put("email", "1025XXXX40@qq.com");
        paramsMap.put("hobby", "編程萌朱,運(yùn)動(dòng)");
        userMapper.saveUser(paramsMap);
        //6.提交事務(wù)
        sqlSession.commit();
        
        //7.關(guān)閉資源
        sqlSession.close();
    }
}

運(yùn)行測試類插入成功


深度截圖_選擇區(qū)域_20190721113023.png

補(bǔ)充:maven pom.xml

<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>com.ways</groupId>
    <artifactId>ssmTest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-servlet-api</artifactId>
            <version>7.0.94</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jsp-api</artifactId>
            <version>7.0.94</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm</artifactId>
            <version>7.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.4</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
            <version>10.2.0.4.0</version>
        </dependency>
    </dependencies>
    
    
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                     <compilerArguments>
                      <extdirs>src\main\webapp\WEB-INF\lib</extdirs>
                      <bootclasspath>/home/zhaohy/software/jdk1.8.0_181/jre/lib/rt.jar</bootclasspath>
                    </compilerArguments> 
                </configuration>
            </plugin>
            <plugin>
              <groupId>org.apache.tomcat.maven</groupId>
              <artifactId>tomcat7-maven-plugin</artifactId>
              <version>2.2</version>
              <configuration>
                <port>8080</port>
                <path>/</path>
              </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <!-- <configuration>
                    <webResources>
                        <webResource>
                            <directory>${project.basedir}/lib</directory>
                            <targetPath>WEB-INF/lib</targetPath>
                            <filtering>false</filtering>
                            <includes>
                                <include>**/*.jar</include>
                            </includes>
                        </webResource>
                    </webResources>
                </configuration> -->
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
            </plugin>
        </plugins>
        
       <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
    
    <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
       <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 
    </properties>
</project>

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"
        xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        version="3.0"
>
  <display-name>ssmTest</display-name>
</web-app>

項(xiàng)目源碼已上傳github地址:
https://github.com/haiyong6/haiyongsRepository/tree/master/code/ssmTest

二宴树、Mybatis整合spring - 有Mapper實(shí)現(xiàn)類

1.在上面的基礎(chǔ)上導(dǎo)入必須的包:
Mybatis-spring
Spring自身的包:
spring-ioc
spring-aop
spring-tx
spring-context
c3p0數(shù)據(jù)庫連接池的包
maven 配置:

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>
        
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.4</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.8.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>

2.編寫Mapper的實(shí)現(xiàn)類:

package com.ways.app.dao.impl;

import java.util.Map;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.ways.app.dao.UserMapper;

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {

    @Override
    public void saveUser(Map<String, Object> paramsMap) {
        this.getSqlSession().insert("com.ways.app.dao.UserMapper.saveUser", paramsMap);
        //不需要事務(wù)提交 mybatis幫忙提交了
    }

}

3.編寫applicationContext.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jee="http://www.springframework.org/schema/jee"
       
       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.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/jee 
            http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
       
       <!-- 讀取jdbc.properties -->
       <context:property-placeholder location="classpath:jdbc.properties"/>
       
       <!-- 創(chuàng)建數(shù)據(jù)源DataSource -->
       <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
              <property name="driverClass" value="${jdbc.driverClassName}" /> 
              <property name="jdbcUrl" value="${jdbc.url}" /> 
              <property name="user" value="${jdbc.username}" /> 
              <property name="password" value="${jdbc.password}" /> 
              <property name="minPoolSize" value="10" /> <!-- 連接池中保留的最小連接數(shù)   -->
              <property name="maxPoolSize" value="100" /> <!-- 連接池中保留的最大連接數(shù)策菜。Default: 15 -->
              <property name="maxIdleTime" value="600" /> <!-- 1800 --><!-- 最大空閑時(shí)間,600秒內(nèi)未使用則連接被丟棄晶疼。若為0則永不丟棄。Default: 0  -->
              <property name="acquireIncrement" value="2" /> 
              <property name="maxStatements" value="0" /> 
              <property name="initialPoolSize" value="10" /> 
              <property name="idleConnectionTestPeriod" value="0" /> <!-- 60 --><!-- 每30秒檢查所有連接池中的空閑連接又憨。Default: 0 -->
              <property name="testConnectionOnCheckout" value="false" /> 
              <property name="acquireRetryAttempts" value="0" /> <!-- 定義在從數(shù)據(jù)庫獲取新連接失敗后重復(fù)嘗試的次數(shù)翠霍。Default: 30 -->
              <property name="acquireRetryDelay" value="1000" /> <!-- 兩次連接中間隔時(shí)間,單位毫秒蠢莺。Default: 1000 -->
              <property name="breakAfterAcquireFailure" value="false" />
       </bean>
       
       <!-- 創(chuàng)建SqlSessionFactory對象 -->
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 關(guān)聯(lián)連接池 -->
            <property name="dataSource" ref="dataSource"/>
            <!-- 加載sql映射文件集 -->
            <property name="configLocation" value="classpath:mapper/sqlMapConfig.xml" />
            <!-- 加載sql映射具體文件路徑 -->
            <!-- <property name="mapperLocations" value="classpath:mapper/*Mappper.xml"/> -->
       </bean>
       
       <!-- 創(chuàng)建CommonMapperImpl對象寒匙,注入SqlSessionFactory -->
        <bean id="userMapper" class="com.ways.app.dao.impl.UserMapperImpl">
            <!-- 注入sqlSessionFactory -->
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>
        
</beans>

jdbc.properties文件:

jdbc.driverClassName=oracle.jdbc.OracleDriver
jdbc.url=jdbc\:oracle\:thin\:@127.0.0.1\:1521\:xe
jdbc.username=zhaohy
jdbc.password=oracle

修改sqlMapConfig.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>  
    <!-- 和spring整合后 environments配置將廢除-->
    <!-- <environments default="development">
        <environment id="development">
            使用jdbc事務(wù)管理
            <transactionManager type="JDBC"/>
            數(shù)據(jù)庫連接池
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.OracleDriver"/>
                <property name="url" value="jdbc:oracle:thin:@172.16.1.37:1521:DBFM"/>
                <property name="username" value="FAWVW"/>
                <property name="password" value="FAWvw419"/>
            </dataSource>
        </environment>
    </environments>  -->
    
    <!-- 查找sql映射文件 -->
    <mappers>
        <mapper resource="com/ways/app/sqlmap/oracle/userMapper.xml"/>
    </mappers>
</configuration>

4.編寫測試類MybatisSpringTest:

package ssmTest;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ways.app.dao.UserMapper;

public class MybatisSpringTest {
 
    @SuppressWarnings("resource")
    @Test
    public void test() {
        //1.加載spring配置
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2.獲取對象
        UserMapper commonMapper = (UserMapper) ac.getBean("userMapper");
        //3.調(diào)用方法
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("userName", "zhaohy1");
        paramsMap.put("sex", 1);
        paramsMap.put("job", "java軟件工程師");
        paramsMap.put("tel", "189xxxx0598");
        paramsMap.put("email", "1025XXXX40@qq.com");
        paramsMap.put("hobby", "編程,運(yùn)動(dòng)");
        commonMapper.saveUser(paramsMap);
    }
}

運(yùn)行可以看到第二條已經(jīng)插入成功躏将!


深度截圖_選擇區(qū)域_20190721121353.png

項(xiàng)目源碼已上傳github:
https://github.com/haiyong6/haiyongsRepository/tree/master/code/ssmTest01

三锄弱、Mybatis整合spring - 沒有Mapper

修改applicationContext.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jee="http://www.springframework.org/schema/jee"
       
       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.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/jee 
            http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
       
       <!-- 讀取jdbc.properties -->
       <context:property-placeholder location="classpath:jdbc.properties"/>
       
       <!-- 創(chuàng)建數(shù)據(jù)源DataSource -->
       <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
              <property name="driverClass" value="${jdbc.driverClassName}" /> 
              <property name="jdbcUrl" value="${jdbc.url}" /> 
              <property name="user" value="${jdbc.username}" /> 
              <property name="password" value="${jdbc.password}" /> 
              <property name="minPoolSize" value="10" /> <!-- 連接池中保留的最小連接數(shù)   -->
              <property name="maxPoolSize" value="100" /> <!-- 連接池中保留的最大連接數(shù)。Default: 15 -->
              <property name="maxIdleTime" value="600" /> <!-- 1800 --><!-- 最大空閑時(shí)間,600秒內(nèi)未使用則連接被丟棄祸憋。若為0則永不丟棄会宪。Default: 0  -->
              <property name="acquireIncrement" value="2" /> 
              <property name="maxStatements" value="0" /> 
              <property name="initialPoolSize" value="10" /> 
              <property name="idleConnectionTestPeriod" value="0" /> <!-- 60 --><!-- 每30秒檢查所有連接池中的空閑連接。Default: 0 -->
              <property name="testConnectionOnCheckout" value="false" /> 
              <property name="acquireRetryAttempts" value="0" /> <!-- 定義在從數(shù)據(jù)庫獲取新連接失敗后重復(fù)嘗試的次數(shù)蚯窥。Default: 30 -->
              <property name="acquireRetryDelay" value="1000" /> <!-- 兩次連接中間隔時(shí)間掸鹅,單位毫秒。Default: 1000 -->
              <property name="breakAfterAcquireFailure" value="false" />
       </bean>
       
       <!-- 創(chuàng)建SqlSessionFactory對象 -->
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 關(guān)聯(lián)連接池 -->
            <property name="dataSource" ref="dataSource"/>
            <!-- 加載sql映射文件集 -->
            <property name="configLocation" value="classpath:mapper/sqlMapConfig.xml" />
            <!-- 加載sql映射具體文件路徑 -->
            <!-- <property name="mapperLocations" value="classpath:mapper/*Mappper.xml"/> -->
       </bean>
       
       <!-- 創(chuàng)建CommonMapperImpl對象拦赠,注入SqlSessionFactory -->
        <!-- <bean id="userMapper" class="com.ways.app.dao.impl.UserMapperImpl">
            注入sqlSessionFactory
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean> -->

        <!-- 配置Mapper接口 -->
        <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
            <!-- 注入mapper接口 -->
            <property name="mapperInterface" value="com.ways.app.dao.UserMapper"/>
            <!-- 注入SqlSessionFactory -->
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>
        
</beans>

項(xiàng)目源碼已上傳github地址:
https://github.com/haiyong6/haiyongsRepository/tree/master/code/ssmTest02

四巍沙、Mybatis整合spring – mapper接口

配置掃描 修改applicationContext.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jee="http://www.springframework.org/schema/jee"
       
       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.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/jee 
            http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
       
       <!-- 讀取jdbc.properties -->
       <context:property-placeholder location="classpath:jdbc.properties"/>
       
       <!-- 創(chuàng)建數(shù)據(jù)源DataSource -->
       <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
              <property name="driverClass" value="${jdbc.driverClassName}" /> 
              <property name="jdbcUrl" value="${jdbc.url}" /> 
              <property name="user" value="${jdbc.username}" /> 
              <property name="password" value="${jdbc.password}" /> 
              <property name="minPoolSize" value="10" /> <!-- 連接池中保留的最小連接數(shù)   -->
              <property name="maxPoolSize" value="100" /> <!-- 連接池中保留的最大連接數(shù)。Default: 15 -->
              <property name="maxIdleTime" value="600" /> <!-- 1800 --><!-- 最大空閑時(shí)間,600秒內(nèi)未使用則連接被丟棄荷鼠。若為0則永不丟棄句携。Default: 0  -->
              <property name="acquireIncrement" value="2" /> 
              <property name="maxStatements" value="0" /> 
              <property name="initialPoolSize" value="10" /> 
              <property name="idleConnectionTestPeriod" value="0" /> <!-- 60 --><!-- 每30秒檢查所有連接池中的空閑連接。Default: 0 -->
              <property name="testConnectionOnCheckout" value="false" /> 
              <property name="acquireRetryAttempts" value="0" /> <!-- 定義在從數(shù)據(jù)庫獲取新連接失敗后重復(fù)嘗試的次數(shù)允乐。Default: 30 -->
              <property name="acquireRetryDelay" value="1000" /> <!-- 兩次連接中間隔時(shí)間矮嫉,單位毫秒牡辽。Default: 1000 -->
              <property name="breakAfterAcquireFailure" value="false" />
       </bean>
       
       <!-- 創(chuàng)建SqlSessionFactory對象 -->
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 關(guān)聯(lián)連接池 -->
            <property name="dataSource" ref="dataSource"/>
            <!-- 加載sql映射文件集 -->
            <property name="configLocation" value="classpath:mapper/sqlMapConfig.xml" />
            <!-- 加載sql映射具體文件路徑 -->
            <!-- <property name="mapperLocations" value="classpath:mapper/*Mappper.xml"/> -->
       </bean>
       
       <!-- 創(chuàng)建CommonMapperImpl對象,注入SqlSessionFactory -->
        <!-- <bean id="userMapper" class="com.ways.app.dao.impl.UserMapperImpl">
            注入sqlSessionFactory
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean> -->
        <!-- 配置Mapper接口 -->
        <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
            注入mapper接口
            <property name="mapperInterface" value="com.ways.app.dao.UserMapper"/>
            注入SqlSessionFactory
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean> -->
        
        <!-- Mappper接口的掃描 
            注意:如果使用Mapper接口包掃描敞临,那么每個(gè)Mapper接口在Spring容器中的id名稱為類名:例如:UserMapper -> userMapper(首字母小寫)
        -->
         <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
               <!-- 配置mapper接口所在的包路徑  會掃描此包以及其子包-->
               <property name="basePackage" value="com.ways.app.dao"/>
         </bean>
        
</beans>

項(xiàng)目源碼已上傳github地址:
https://github.com/haiyong6/haiyongsRepository/tree/master/code/ssmTest03

五态辛、Mybatis 整合spring – 整合jdbc事務(wù)

1.修改applicationContext.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jee="http://www.springframework.org/schema/jee"
       
       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.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/jee 
            http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
       
       <!-- 讀取jdbc.properties -->
       <context:property-placeholder location="classpath:jdbc.properties"/>
       
       <!-- 創(chuàng)建數(shù)據(jù)源DataSource -->
       <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
              <property name="driverClass" value="${jdbc.driverClassName}" /> 
              <property name="jdbcUrl" value="${jdbc.url}" /> 
              <property name="user" value="${jdbc.username}" /> 
              <property name="password" value="${jdbc.password}" /> 
              <property name="minPoolSize" value="10" /> <!-- 連接池中保留的最小連接數(shù)   -->
              <property name="maxPoolSize" value="100" /> <!-- 連接池中保留的最大連接數(shù)。Default: 15 -->
              <property name="maxIdleTime" value="600" /> <!-- 1800 --><!-- 最大空閑時(shí)間,600秒內(nèi)未使用則連接被丟棄挺尿。若為0則永不丟棄奏黑。Default: 0  -->
              <property name="acquireIncrement" value="2" /> 
              <property name="maxStatements" value="0" /> 
              <property name="initialPoolSize" value="10" /> 
              <property name="idleConnectionTestPeriod" value="0" /> <!-- 60 --><!-- 每30秒檢查所有連接池中的空閑連接。Default: 0 -->
              <property name="testConnectionOnCheckout" value="false" /> 
              <property name="acquireRetryAttempts" value="0" /> <!-- 定義在從數(shù)據(jù)庫獲取新連接失敗后重復(fù)嘗試的次數(shù)编矾。Default: 30 -->
              <property name="acquireRetryDelay" value="1000" /> <!-- 兩次連接中間隔時(shí)間熟史,單位毫秒。Default: 1000 -->
              <property name="breakAfterAcquireFailure" value="false" />
       </bean>
       
       <!-- 創(chuàng)建SqlSessionFactory對象 -->
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 關(guān)聯(lián)連接池 -->
            <property name="dataSource" ref="dataSource"/>
            <!-- 加載sql映射文件集 -->
            <property name="configLocation" value="classpath:mapper/sqlMapConfig.xml" />
            <!-- 加載sql映射具體文件路徑 -->
            <!-- <property name="mapperLocations" value="classpath:mapper/*Mappper.xml"/> -->
       </bean>
       
       <!-- 創(chuàng)建CommonMapperImpl對象窄俏,注入SqlSessionFactory -->
        <!-- <bean id="userMapper" class="com.ways.app.dao.impl.UserMapperImpl">
            注入sqlSessionFactory
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean> -->
        <!-- 配置Mapper接口 -->
        <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
            注入mapper接口
            <property name="mapperInterface" value="com.ways.app.dao.UserMapper"/>
            注入SqlSessionFactory
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean> -->
        
        <!-- Mappper接口的掃描 
            注意:如果使用Mapper接口包掃描蹂匹,那么每個(gè)Mapper接口在Spring容器中的id名稱為類名:例如:UserMapper -> userMapper(首字母小寫)
        -->
         <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
               <!-- 配置mapper接口所在的包路徑  會掃描此包以及其子包-->
               <property name="basePackage" value="com.ways.app.dao"/>
         </bean>
         
         <!-- 開啟Spring ioc注解掃描 -->
        <context:component-scan base-package="com.ways.app"/>
        
        <!-- 開啟spring的事務(wù) -->
        <!-- 事務(wù)管理器 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <!-- 注入dataSource -->
            <property name="dataSource" ref="dataSource"/>
        </bean>
        <!-- 啟用Spring的事務(wù)注解 -->
        <tx:annotation-driven transaction-manager="transactionManager"/>
        
</beans>

2.編寫業(yè)務(wù)接口和實(shí)現(xiàn)方法,并在業(yè)務(wù)方法上添加注解@Transactional
UserService

package com.ways.app.service;

import java.util.Map;

public interface UserService {
    public void saveUser(Map<String, Object> paramsMap);
}

UserServiceImpl

package com.ways.app.service.impl;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ways.app.dao.UserMapper;
import com.ways.app.service.UserService;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
    //注入Mapper對象
    @Resource
    private UserMapper userMapper;
    @Override
    public void saveUser(Map<String, Object> paramsMap) {
        userMapper.saveUser(paramsMap);
        int i = 100/0;
        userMapper.saveUser(paramsMap);

    }

}

此處故意寫了一個(gè)int i = 100/0的異常凹蜈,為了測試事務(wù)是否生效限寞,如果生效的話 這兩次插入都不會被插入數(shù)據(jù)庫

3.測試方法:

package ssmTest;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ways.app.service.UserService;

public class MybatisSpringTest {
 
    @Test
    public void test1() {
          //1.加載spring配置
            ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
            //2.獲取對象
            UserService commonService = (UserService) ac.getBean("userService");
            Map<String, Object> paramsMap = new HashMap<String, Object>();
            paramsMap.put("userName", "zhaohy4");
            paramsMap.put("sex", 1);
            paramsMap.put("job", "java軟件工程師");
            paramsMap.put("tel", "189xxxx0598");
            paramsMap.put("email", "1025XXXX40@qq.com");
            paramsMap.put("hobby", "編程,運(yùn)動(dòng)");
            commonService.saveUser(paramsMap);
        }
}

運(yùn)行測試方法 junit報(bào)錯(cuò)仰坦,分母不能為0履植,通過數(shù)據(jù)庫查表得知兩條都沒有插入成功,說明事務(wù)控制成功悄晃。事務(wù)注解可以對一個(gè)單一的方法也可以對整個(gè)類控制玫霎。

項(xiàng)目源碼已上傳github:
https://github.com/haiyong6/haiyongsRepository/tree/master/code/ssmTest04

六、整合SpringMVC

1.導(dǎo)入springMVC的包
2.配置web.xml
1)啟動(dòng)spring,加載applicationContext.xml
2)啟動(dòng)springmvc,加載spring-mvc.xml

maven配置:

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

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"
        xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        version="3.0"
>
  <display-name>ssmTest05</display-name>
  
  <!-- 啟動(dòng)spring 監(jiān)聽器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- 修改路徑:使spring讀入applicationContext.xml配置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classPath:applicationContext.xml</param-value>
  </context-param>
  
  <!-- 啟動(dòng)springmvc -->
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 參數(shù):讀取spring-mvc.xml -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classPath:spring-mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>*.do</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>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

配置spring-mvc.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:jee="http://www.springframework.org/schema/jee"
       
       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.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/jee 
            http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
       
       <!-- 掃描Controller所在的包 -->
       <context:component-scan base-package="com.ways.app.web.controller"/>
       
       <!-- 注解驅(qū)動(dòng) -->
       <mvc:annotation-driven></mvc:annotation-driven>
        
        <!-- 視圖解析器:簡化在Controller類編寫的視圖路徑 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- 前綴 -->
            <property name="prefix" value="/WEB-INF/pages/"/>
            <!-- 后綴 -->
            <property name="suffix" value=".jsp"/>
        </bean>
                
</beans>

編寫UserController:

package com.ways.app.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UserController {
    
    @RequestMapping("/user/test")
    public String test() {
        
        return "test";
    }

}

在WEB-INF/pages/下編寫test.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>Hello SpringMVC!</h1>
</body>
</html>

請求/user/test.do接口妈橄,成功跳轉(zhuǎn)到test.jsp,springmvc配置成功庶近!


深度截圖_選擇區(qū)域_20190721163515.png

在controller寫一個(gè)保存用戶的方法 測試一下能不能插入數(shù)據(jù):

package com.ways.app.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ways.app.service.UserService;
@Controller
public class UserController {
    @Resource
    public UserService userService;
    @RequestMapping("/user/test")
    public String test() {
        
        return "test";
    }
    
    @RequestMapping("/user/saveUser")
    public void saveUser() {
        
        Map<String, Object> paramsMap = new HashMap<String ,Object>();
        paramsMap.put("userName", "zhaohy4");
        paramsMap.put("sex", 1);
        paramsMap.put("job", "java軟件工程師");
        paramsMap.put("tel", "189xxxx0598");
        paramsMap.put("email", "1025XXXX40@qq.com");
        paramsMap.put("hobby", "編程,運(yùn)動(dòng)");
        userService.saveUser(paramsMap);
    }

}

運(yùn)行tomcat 請求/user/saveUser.do
可以看到數(shù)據(jù)庫里已經(jīng)插入了一條信息


深度截圖_選擇區(qū)域_20190721164339.png

至此眷蚓,一個(gè)完整的簡單ssm項(xiàng)目就已經(jīng)搭建完成啦~

項(xiàng)目源碼已上傳github:
https://github.com/haiyong6/haiyongsRepository/tree/master/code/ssmTest05

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末鼻种,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子溪椎,更是在濱河造成了極大的恐慌普舆,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,816評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件校读,死亡現(xiàn)場離奇詭異沼侣,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)歉秫,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,729評論 3 385
  • 文/潘曉璐 我一進(jìn)店門蛾洛,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事轧膘〕” “怎么了?”我有些...
    開封第一講書人閱讀 158,300評論 0 348
  • 文/不壞的土叔 我叫張陵谎碍,是天一觀的道長鳞滨。 經(jīng)常有香客問我,道長蟆淀,這世上最難降的妖魔是什么拯啦? 我笑而不...
    開封第一講書人閱讀 56,780評論 1 285
  • 正文 為了忘掉前任,我火速辦了婚禮熔任,結(jié)果婚禮上褒链,老公的妹妹穿的比我還像新娘。我一直安慰自己疑苔,他們只是感情好甫匹,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,890評論 6 385
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著惦费,像睡著了一般兵迅。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上趁餐,一...
    開封第一講書人閱讀 50,084評論 1 291
  • 那天喷兼,我揣著相機(jī)與錄音,去河邊找鬼后雷。 笑死,一個(gè)胖子當(dāng)著我的面吹牛吠各,可吹牛的內(nèi)容都是我干的臀突。 我是一名探鬼主播,決...
    沈念sama閱讀 39,151評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼贾漏,長吁一口氣:“原來是場噩夢啊……” “哼候学!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起纵散,我...
    開封第一講書人閱讀 37,912評論 0 268
  • 序言:老撾萬榮一對情侶失蹤梳码,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后伍掀,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體掰茶,經(jīng)...
    沈念sama閱讀 44,355評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,666評論 2 327
  • 正文 我和宋清朗相戀三年蜜笤,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了濒蒋。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,809評論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖沪伙,靈堂內(nèi)的尸體忽然破棺而出瓮顽,到底是詐尸還是另有隱情,我是刑警寧澤围橡,帶...
    沈念sama閱讀 34,504評論 4 334
  • 正文 年R本政府宣布暖混,位于F島的核電站,受9級特大地震影響翁授,放射性物質(zhì)發(fā)生泄漏儒恋。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,150評論 3 317
  • 文/蒙蒙 一黔漂、第九天 我趴在偏房一處隱蔽的房頂上張望诫尽。 院中可真熱鬧,春花似錦炬守、人聲如沸牧嫉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽酣藻。三九已至,卻和暖如春鳍置,著一層夾襖步出監(jiān)牢的瞬間辽剧,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,121評論 1 267
  • 我被黑心中介騙來泰國打工税产, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留怕轿,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,628評論 2 362
  • 正文 我出身青樓辟拷,卻偏偏與公主長得像撞羽,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子衫冻,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,724評論 2 351

推薦閱讀更多精彩內(nèi)容