java SSM框架整合实战

2019-07-21  本文已影响0人  haiyong6

这次的ssm整合比较详细,会从单独的mybatis连接数据库开始,基本会分为以下几个步骤:

1.单独使用mybatis

2.Mybatis整合spring - 有Mapper实现类

3.Mybatis整合spring – 没有Mapper实现类

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

5.Mybatis 整合spring – 整合jdbc事务

6.整合springmvc

首先,对ssm整合有个大体的认识:

表现层:SpringMVC

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

业务层:Spring

包:spring-ioc Spring-aop Spring-tx Spring-test
配置文件:applicationContext.xml
添加关于mybatis的配置

持久层:mybatis

包:mybatis自身核心包 Mysql数据库驱动包 C3p0连接池 Mybatis-spring的包
配置文件:sqlMapConfig.xml userMapperxml

一、单独使用mybatis

1.导入必须的包:
a)Mybatis自身核心jar:mybatis-3.4.4.jar
b)Log4j日志jar:log4j-1.2.17.jar
c)Oracle驱动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因为版权关系在maven远程仓库中只有目录没有jar包的,如果添加配置报错要手动下载相应jar包放在本地仓库的相应文件夹就好啦。

2.建立测试数据库表

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.建立实体类
也可以直接用HashMap映射 对于比较简单的查询我比较习惯用这个
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事务管理 -->
            <transactionManager type="JDBC"/>
            <!-- 数据库连接池 -->
            <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.创建SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        // 加载sqlMapConfig.xml文件
        InputStream ins = Resources.getResourceAsStream("sqlMapConfig.xml");
        
        
        //2.创建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", "编程,运动");
        userMapper.saveUser(paramsMap);
        //6.提交事务
        sqlSession.commit();
        
        //7.关闭资源
        sqlSession.close();
    }
}

运行测试类插入成功


深度截图_选择区域_20190721113023.png

补充: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>

项目源码已上传github地址:
https://github.com/haiyong6/haiyongsRepository/tree/master/code/ssmTest

二、Mybatis整合spring - 有Mapper实现类

1.在上面的基础上导入必须的包:
Mybatis-spring
Spring自身的包:
spring-ioc
spring-aop
spring-tx
spring-context
c3p0数据库连接池的包
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的实现类:

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);
        //不需要事务提交 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"/>
       
       <!-- 创建数据源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" /> <!-- 连接池中保留的最小连接数   -->
              <property name="maxPoolSize" value="100" /> <!-- 连接池中保留的最大连接数。Default: 15 -->
              <property name="maxIdleTime" value="600" /> <!-- 1800 --><!-- 最大空闲时间,600秒内未使用则连接被丢弃。若为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" /> <!-- 定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
              <property name="acquireRetryDelay" value="1000" /> <!-- 两次连接中间隔时间,单位毫秒。Default: 1000 -->
              <property name="breakAfterAcquireFailure" value="false" />
       </bean>
       
       <!-- 创建SqlSessionFactory对象 -->
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 关联连接池 -->
            <property name="dataSource" ref="dataSource"/>
            <!-- 加载sql映射文件集 -->
            <property name="configLocation" value="classpath:mapper/sqlMapConfig.xml" />
            <!-- 加载sql映射具体文件路径 -->
            <!-- <property name="mapperLocations" value="classpath:mapper/*Mappper.xml"/> -->
       </bean>
       
       <!-- 创建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事务管理
            <transactionManager type="JDBC"/>
            数据库连接池
            <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.调用方法
        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", "编程,运动");
        commonMapper.saveUser(paramsMap);
    }
}

运行可以看到第二条已经插入成功!


深度截图_选择区域_20190721121353.png

项目源码已上传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"/>
       
       <!-- 创建数据源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" /> <!-- 连接池中保留的最小连接数   -->
              <property name="maxPoolSize" value="100" /> <!-- 连接池中保留的最大连接数。Default: 15 -->
              <property name="maxIdleTime" value="600" /> <!-- 1800 --><!-- 最大空闲时间,600秒内未使用则连接被丢弃。若为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" /> <!-- 定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
              <property name="acquireRetryDelay" value="1000" /> <!-- 两次连接中间隔时间,单位毫秒。Default: 1000 -->
              <property name="breakAfterAcquireFailure" value="false" />
       </bean>
       
       <!-- 创建SqlSessionFactory对象 -->
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 关联连接池 -->
            <property name="dataSource" ref="dataSource"/>
            <!-- 加载sql映射文件集 -->
            <property name="configLocation" value="classpath:mapper/sqlMapConfig.xml" />
            <!-- 加载sql映射具体文件路径 -->
            <!-- <property name="mapperLocations" value="classpath:mapper/*Mappper.xml"/> -->
       </bean>
       
       <!-- 创建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>

项目源码已上传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"/>
       
       <!-- 创建数据源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" /> <!-- 连接池中保留的最小连接数   -->
              <property name="maxPoolSize" value="100" /> <!-- 连接池中保留的最大连接数。Default: 15 -->
              <property name="maxIdleTime" value="600" /> <!-- 1800 --><!-- 最大空闲时间,600秒内未使用则连接被丢弃。若为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" /> <!-- 定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
              <property name="acquireRetryDelay" value="1000" /> <!-- 两次连接中间隔时间,单位毫秒。Default: 1000 -->
              <property name="breakAfterAcquireFailure" value="false" />
       </bean>
       
       <!-- 创建SqlSessionFactory对象 -->
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 关联连接池 -->
            <property name="dataSource" ref="dataSource"/>
            <!-- 加载sql映射文件集 -->
            <property name="configLocation" value="classpath:mapper/sqlMapConfig.xml" />
            <!-- 加载sql映射具体文件路径 -->
            <!-- <property name="mapperLocations" value="classpath:mapper/*Mappper.xml"/> -->
       </bean>
       
       <!-- 创建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接口包扫描,那么每个Mapper接口在Spring容器中的id名称为类名:例如:UserMapper -> userMapper(首字母小写)
        -->
         <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
               <!-- 配置mapper接口所在的包路径  会扫描此包以及其子包-->
               <property name="basePackage" value="com.ways.app.dao"/>
         </bean>
        
</beans>

项目源码已上传github地址:
https://github.com/haiyong6/haiyongsRepository/tree/master/code/ssmTest03

五、Mybatis 整合spring – 整合jdbc事务

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"/>
       
       <!-- 创建数据源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" /> <!-- 连接池中保留的最小连接数   -->
              <property name="maxPoolSize" value="100" /> <!-- 连接池中保留的最大连接数。Default: 15 -->
              <property name="maxIdleTime" value="600" /> <!-- 1800 --><!-- 最大空闲时间,600秒内未使用则连接被丢弃。若为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" /> <!-- 定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
              <property name="acquireRetryDelay" value="1000" /> <!-- 两次连接中间隔时间,单位毫秒。Default: 1000 -->
              <property name="breakAfterAcquireFailure" value="false" />
       </bean>
       
       <!-- 创建SqlSessionFactory对象 -->
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 关联连接池 -->
            <property name="dataSource" ref="dataSource"/>
            <!-- 加载sql映射文件集 -->
            <property name="configLocation" value="classpath:mapper/sqlMapConfig.xml" />
            <!-- 加载sql映射具体文件路径 -->
            <!-- <property name="mapperLocations" value="classpath:mapper/*Mappper.xml"/> -->
       </bean>
       
       <!-- 创建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接口包扫描,那么每个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的事务 -->
        <!-- 事务管理器 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <!-- 注入dataSource -->
            <property name="dataSource" ref="dataSource"/>
        </bean>
        <!-- 启用Spring的事务注解 -->
        <tx:annotation-driven transaction-manager="transactionManager"/>
        
</beans>

2.编写业务接口和实现方法,并在业务方法上添加注解@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);

    }

}

此处故意写了一个int i = 100/0的异常,为了测试事务是否生效,如果生效的话 这两次插入都不会被插入数据库

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", "编程,运动");
            commonService.saveUser(paramsMap);
        }
}

运行测试方法 junit报错,分母不能为0,通过数据库查表得知两条都没有插入成功,说明事务控制成功。事务注解可以对一个单一的方法也可以对整个类控制。

项目源码已上传github:
https://github.com/haiyong6/haiyongsRepository/tree/master/code/ssmTest04

六、整合SpringMVC

1.导入springMVC的包
2.配置web.xml
1)启动spring,加载applicationContext.xml
2)启动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>
  
  <!-- 启动spring 监听器-->
  <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>
  
  <!-- 启动springmvc -->
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 参数:读取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"/>
       
       <!-- 注解驱动 -->
       <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接口,成功跳转到test.jsp,springmvc配置成功!


深度截图_选择区域_20190721163515.png

在controller写一个保存用户的方法 测试一下能不能插入数据:

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", "编程,运动");
        userService.saveUser(paramsMap);
    }

}

运行tomcat 请求/user/saveUser.do
可以看到数据库里已经插入了一条信息


深度截图_选择区域_20190721164339.png

至此,一个完整的简单ssm项目就已经搭建完成啦~

项目源码已上传github:
https://github.com/haiyong6/haiyongsRepository/tree/master/code/ssmTest05

上一篇下一篇

猜你喜欢

热点阅读