Spring系列Spring与MyBatis框架整合

Posted 一宿君

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring系列Spring与MyBatis框架整合相关的知识,希望对你有一定的参考价值。

7 搭建Spring与MyBatis的集成环境

要实现Spring与MyBatis的整合,很明显需要这两个框架各自的jar包,以及整合两个框架的中间包mybatis-spring.jar:

我们使用maven创建web项目spring-mybatis,只需要引入相关jar的依赖即可:
在这里插入图片描述

  • 相关依赖文件:
    <!--druid连接池-->
        <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>1.2.6</version>
        </dependency>
    
        <!--spring上下文-->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>5.3.0</version>
        </dependency>
    
        <!--aspectJweaver-->
        <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>1.9.0</version>
          <scope>runtime</scope>
        </dependency>
    
    
    
        <!--spring-jdbc 此处的版本号尽量和spring上下文的版本号保持一致-->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>5.3.0</version>
        </dependency>
    
        <!--mybatis-->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.5.7</version>
        </dependency>
    
        <!--spring-mybatis-->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>2.0.3</version>
        </dependency>
    
        <!--oracle-->
        <dependency>
          <groupId>com.oracle</groupId>
          <artifactId>ojdbc6</artifactId>
          <version>11.2.0.2.0</version>
          <scope>compile</scope>
        </dependency>
    
    
        <!--log4j日志文件-->
        <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.17</version>
        </dependency>
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.7.21</version>
        </dependency>
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.7.21</version>
        </dependency>
    
        <!--javaee-api中含有mail邮件api-->
        <dependency>
          <groupId>javax</groupId>
          <artifactId>javaee-api</artifactId>
          <version>8.0</version>
        </dependency>
    
        <!--单元测试-->
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>test</scope>
        </dependency>
    

在spring-context上下文依赖中,就已经包含了spring常常用的核心标签依赖,eg:aop、beans、core、expression等。

我们虽然引入了spring-jdbc相关依赖,但是我们并不使用它来连接数据库,只是为了引入其依赖下的tx标签的依赖文件,我们使用alibaba为我们提供的druid连接池(德鲁斯)连接数据库,因为其功能强悍,而且可以配置许多连接参数,配置最大连接数和最大空闲等待数等。

7.1 编写database.properties配置文件

#数据库驱动
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
#数据库
jdbc.url=jdbc:oracle:thin:localhost:1521:orcl
#用户名
jdbc.username=ebuy
#密码
jdbc.password=123456
#别名方式,扩展插件,监控统计用的filter:stat,日志用的filter:log4j,防御sql注入的filter:wall
jdbc.filters=stat 
#最大连接数
jdbc.maxActive=300
#初始化连接数
jdbc.initialSize=2
#获取连接最大等待时间
jdbc.maxWait=60000
#最小连接数
jdbc.minIdle=1
#检测连接有效性的时间间隔
jdbc.timeBetweenEvictionRunsMillis=60000
#连接保持空闲而不被驱逐的最长时间
jdbc.minEvictableIdleTimeMillis=300000
#连接有效性,检测sql
jdbc.validationQuery=SELECT  * from dual
#定时检测空闲连接有效性
jdbc.testWhileIdle=true
#检测获取的连接的有效性
jdbc.testOnBorrow=false
#检测要归还的连接的有效性
jdbc.testOnReturn=false
#是否缓存preparedStatement,即PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
jdbc.poolPreparedStatements=false
jdbc.maxPoolPreparedStatementPerConnectionSize=50

7.2 log4j.properties日志输出文件

log4j.rootLogger=DEBUG,CONSOLE
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.com.dao=debug
log4j.logger.com.ibatis=debug 
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug 
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug 
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug 
log4j.logger.java.sql.Connection=debug 
log4j.logger.java.sql.Statement=debug 
log4j.logger.java.sql.PreparedStatement=debug 
log4j.logger.java.sql.ResultSet=debug 
######################################################################################
# Console Appender  \\u65e5\\u5fd7\\u5728\\u63a7\\u5236\\u8f93\\u51fa\\u914d\\u7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%p] %d %c - %m%n

7.3 mybatis-conf.xml配置文件(此文件中可以什么都不写,单纯为了以后mybatis扩展业务,也可以稍加配置常用机制)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <settings>
        <!--设置MyBatis控制台输出为log4j日志文件-->
        <setting name="logImpl" value="log4j"/>
        <!--开启二级缓存-->
        <setting name="cacheEnabled" value="true"/>
    </settings>

    <!--开启类名简写——别名-->
    <typeAliases>
        <package name="com.pojo"/>
    </typeAliases>

</configuration>

7.4 Spring的核心配置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:bean="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

    <!--加载连接Oracle数据库的参数配置文件-->
    <context:property-placeholder location="database.properties"/>

    <!--配置数据库连接池(使用alibaba提供的druid连接池——德鲁斯)-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!--此处我们不适用spring内部提供的jdbc连接数据库,所以jdbc.driverClassName不需要引入-->
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="filters" value="${jdbc.filters}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
        <property name="initialSize" value="${jdbc.initialSize}"/>
        <property name="maxWait" value="${jdbc.maxWait}"/>
        <property name="minIdle" value="${jdbc.minIdle}"/>
        <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/>
        <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/>
        <property name="validationQuery" value="${jdbc.validationQuery}"/>
        <property name="testWhileIdle" value="${jdbc.testWhileIdle}"/>
        <property name="testOnBorrow" value="${jdbc.testOnBorrow}"/>
        <property name="testOnReturn" value="${jdbc.testOnReturn}"/>
        <property name="poolPreparedStatements" value="${jdbc.poolPreparedStatements}"/>
        <property name="maxPoolPreparedStatementPerConnectionSize"
                  value="${jdbc.maxPoolPreparedStatementPerConnectionSize}"/>
    </bean>

</beans>

7.5 创建com.pojo.SystemUser实体类

	package com.pojo;
	
	import java.io.Serializable;
	
	/**
	 * 用户实体
	 */
	public class SystemUser implements Serializable {
	
	    private String userinfo_uid;
	    private String userinfo_loginid;
	    private String userinfo_name;
	    private String userinfo_password;
	    private String userinfo_sex;
	    private String userinfo_email;
	    private String userinfo_mobile;
	    private int userinfo_status;
	
	    @Override
	    public String toString() {
	        return "SystemUser{" +
	                "userinfo_uid='" + userinfo_uid + '\\'' +
	                ", userinfo_loginid='" + userinfo_loginid + '\\'' +
	                ", userinfo_name='" + userinfo_name + '\\'' +
	                ", userinfo_password='" + userinfo_password + '\\'' +
	                ", userinfo_sex='" + userinfo_sex + '\\'' +
	                ", userinfo_email='" + userinfo_email + '\\'' +
	                ", userinfo_mobile='" + userinfo_mobile + '\\'' +
	                ", userinfo_status=" + userinfo_status +
	                '}';
	    }
	
	    public String getUserinfo_uid() {
	        return userinfo_uid;
	    }
	
	    public void setUserinfo_uid(String userinfo_uid) {
	        this.userinfo_uid = userinfo_uid;
	    }
	
	    public String getUserinfo_loginid() {
	        return userinfo_loginid;
	    }
	
	    public void setUserinfo_loginid(String userinfo_loginid) {
	        this.userinfo_loginid = userinfo_loginid;
	    }
	
	    public String getUserinfo_name() {
	        return userinfo_name;
	    }
	
	    public void setUserinfo_name(String userinfo_name) {
	        this.userinfo_name = userinfo_name;
	    }
	
	    public String getUserinfo_password() {
	        return userinfo_password;
	    }
	
	    public void setUserinfo_password(String userinfo_password) {
	        this.userinfo_password = userinfo_password;
	    }
	
	    public String getUserinfo_sex() {
	        return userinfo_sex;
	    }
	
	    public void setUserinfo_sex(String userinfo_sex) {
	        this.userinfo_sex = userinfo_sex;
	    }
	
	    public String getUserinfo_email() {
	        return userinfo_email;
	    }
	
	    public void setUserinfo_email(String userinfo_email) {
	        this.userinfo_email = userinfo_email;
	    }
	
	    public String getUserinfo_mobile() {
	        return userinfo_mobile;
	    }
	
	    public void setUserinfo_mobile(String userinfo_mobile) {
	        this.userinfo_mobile = userinfo_mobile;
	    }
	
	    public int getUserinfo_status() {
	        return userinfo_status;
	    }
	
	    public void setUserinfo_status(int userinfo_status) {
	        this.userinfo_status = userinfo_status;
	    }
	}

7.6 创建com.dao.SystemUserMapper映射接口类,并创建登陆和注册用户方法

package com.dao;

import com.pojo.SystemUser;

/**
 * @author 一宿君(CSDN : qq_52596258)
 * @date 2021-07-08 10:25:52
 * 用户数据访问接口
 */
public interface SystemUserMapper {

    /**
     * 根据登录id和密码
     * @param systemUser
     * @return
     */
    SystemUser login(SystemUser systemUser);

    /**
     * 用户注册
     * @param systemUser
     * @return
     */
    int save(Syste8 mUser systemUser);
}

7.7 创建com.dao.SystemUserMapper.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">

<!--namespace是命名空间,要与对应的接口的路径保持一致(如果没有创建该接口,MyBatis在内部编译时会自动创建)-->
<mapper namespace="com.dao.SystemUserMapper">
    <!--开启字段自动映射-->
    <resultMap id="userMap" type="com.pojo.SystemUser" autoMapping="true">
        <!--<result property="userinfo_uid" column="userinfo_uid"/>
        <result property="userinfo_loginid" column="userinfo_loginid"/>
        <result property="userinfo_name" column="userinfo_name"/>
        <result property="userinfo_password" column="userinfo_password"/>
        <result property="userinfo_sex" column="userinfo_sex"/>
        <result property="userinfo_email" column="userinfo_email"/>
        <result property="userinfo_mobile" column="userinfo_mobile"/>
        <result property="userinfo_status" column="userinfo_status"/>-->
    </resultMap>

    <!--关联查询表system_userinfo和表system_role,查询结果是多对一,也就是多个用户对应一个角色-->
    <select id="login" parameterType="com.pojo.SystemUser" resultMap="userMap">
        select * from system_userinfo where userinfo_loginid = #{userinfo_loginid} and userinfo_password = #{userinfo_password}
    </select>

    <!--用户注册-->
    <insert id="save" parameterType="com.pojo.SystemUser">
        <selectKey keyProperty="userinfo_uid" resultType="String" order="BEFORE">
            select seq_user_id.nextval from dual
        </selectKey>
        insert into system_userinfo(userinfo_uid,userinfo_loginid,userinfo_name,userinfo_password,
        userinfo_sex,userinfo_email,userinfo_mobile,userinfo_status)
        values(seq_user_id.nextval,#{userinfo_loginid},#{userinfo_name},#{userinfo_password},#{userinfo_sex},#{userinfo_email},#{userinfo_mobile},#{userinfo_status})
    Spring全家桶系列--SpringBoot与Mybatis结合

spring boot 集成 Mybatis,JPA

mybatis与spring整合时读取properties问题的解决

Spring全家桶系列--SpringBoot与Mybatis结合

[转]狂神说SSM框架系列连载

SSM 三大框架系列:Spring 5 + Spring MVC 5 + MyBatis 3.5 整合(附源码)