美文网首页Mybatis
SpringMVC整合Mybatis具体实现

SpringMVC整合Mybatis具体实现

作者: Michaelhbjian | 来源:发表于2018-05-31 16:02 被阅读0次

    为了减少项目的工作量以及快速开发,现在引入ROM层框架Mybatis,让开发人员更加专注于业务逻辑和SQL语句的编写。

    一、Mybatis介绍

    MyBatis是支持定制化SQL、存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。 MyBatis使用简单的XML或注解用于配置和原始映射,将接口和Java的POTJOS(Plain
    Old Java Objects,普通的Java对象)映射成数据库中的记录。

    Mybatis与JDBC相比的优势:

    • 1、简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
    • 2、灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql基本上可以实现我们不使用数据访问框架可以实现的所有功能,或许更多。
    • 3、解除sql与程序代码的耦合 :通过提供DAL层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
    • 4、提供映射标签,支持对象与数据库的orm字段关系映射
    • 5、提供对象关系映射标签,支持对象关系组建维护
    • 6、提供xml标签,支持编写动态sql

    Mybatis与JDBC相比如何选择:

    ​ 通过以上对比mybatis有比较明显的优势,建议选择mybatis。

    另外,Mybatis提供了一下比较JDBC没有的功能:

    • 1、Mybatis提供分页插件pageHelper,可以在中间件这边轻松的实现分页操作。
    • 2、Mybatis提供了连接池管理,可以不必再去管连接池的开启和资源关闭。
    • 3、Mybatis提供了事务管理
    • 4、Mybatis提供了缓存机制,可以将经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上查询,从缓存中查询,从而提高查询效率。

    二、与现在项目中的JDBC对比

    JDBC代码量

    public List<LogResult> getLogRecord(LogReceive logReceive) throws SQLException {
            Connection connection = null;
            List<LogResult> list = new ArrayList<>();
            String sql = null;
                sql = "XXXX";
                System.out.println(sql);
                connection = getDataSource().getConnection();
                PreparedStatement ps = connection.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();
                ...
                    //将对象加入到list集合中
                    list.add(logResult);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.close();
                }
            }
            return list;
        }
    

    Mybatis代码量

    <!--namespace为指定的mapper接口-->
    <mapper namespace="trace.db.mapper.LogMapper">
               #id:SQL语句的唯一标识
               #parameter:指定传入的参数类型
               #resultType:返回结果集类型
                <select id="selectByPrimaryKey" parameterType="java.lang.Integer"
                        resultType="com.trace.app.framework.toolsmodel.LogResult">
                        SELECT * FROM t_logs WHERE company_sid = #{companySid}
                </select>
    </mapper>
    

    很明显,mybatis的代码量比原生的JDBC少了很多,大大提高了开发效率!

    三、引入步骤

    1.在pom.xml中加入mybatis核心包和mybatis-spring包

            <!-- mybatis核心包 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <!-- mybatis/spring包 -->
            <!--官网英文材料:http://www.mybatis.org/spring/-->
            <!--官网中文资料:http://www.mybatis.org/spring/zh/index.html-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>${mybatis-spring.version}</version>
            </dependency>
           
            <mybatis.version>3.4.3</mybatis.version>
            <mybatis-spring.version>1.3.1</mybatis-spring.version>
    

    2.新建mybatisConfig.xml配置文件

    LL\application\web\WEB-INF\spring\mybatisConfig.xml路径上新建mybatisConfig.xml文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans default-merge="true" xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:task="http://www.springframework.org/schema/task"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
           xmlns:util="http://www.springframework.org/schema/util">
        
        <!--引入数据源-->
        <import resource="../database/dataSource_Connection.xml"/>
    
        <!-- mybatis文件配置,扫描所有mapper文件 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" scope="prototype">
            <!--配置数据源-->
            <property name="dataSource" ref="dataSource"/>
            
            <!--mybatis配置文件
            classpath相对于resource来说的,所以我将xml文件都放在resource下的目录了
            -->
            <property name="configLocation" value="classpath:mybatis/mybatis.xml"/>
            <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        </bean>
        <!---->
    
        <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
            <constructor-arg index="0" ref="sqlSessionFactory" />
        </bean>
    
        <!-- mapper 接口所在包名,Spring会自动查找其下的类 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!--给出需要扫描的接口-->
            <property name="basePackage" value="trace.db.mapper"/>
            <!--注入sqlSessionFactory-->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        </bean>
    </beans>
    

    3.新建mybatis.xml文件

    这个文件在LL\src\main\resources\mybatis\mybatis.xml,

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <settings>
            <!-- 开启mybatis缓存设置,一般都是true -->
            <setting name="cacheEnabled" value="true"/>
            <!--延迟加载的全局开关-->
            <setting name="lazyLoadingEnabled" value="false"/>
            <!--设置超时时间-->
            <setting name="defaultStatementTimeout" value="3000"/>
            <!--本地缓存机制-->
            <setting name="localCacheScope" value="STATEMENT"/>
            <setting name="defaultExecutorType" value="SIMPLE"/>
            <setting name="mapUnderscoreToCamelCase" value="true"/>
            <!--允许JDBC支持自动生成主键,需要驱动的兼容-->
            <setting name="useGeneratedKeys" value="true"/>
        </settings>
    </configuration>
    

    4.新建LogMapper.java接口类

    package trace.db.mapper;
    
    import com.trace.app.framework.toolsmodel.LogResult;
    import org.springframework.stereotype.Repository;
    
    import java.util.List;
    
    /**
     * @author zhoujian123@hotmail.com 2018/4/12 21:50
     */
    @Repository
    public interface LogMapper {
    
         List<LogResult> selectByPrimaryKey(Integer companySid);
    }
    

    5.新建接口对应的映射文件

    <?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为指定的mapper接口-->
    <mapper namespace="trace.db.mapper.LogMapper">
               #id:SQL语句的唯一标识
               #parameter:指定传入的参数类型
               #resultType:返回结果集类型
                <select id="selectByPrimaryKey" parameterType="java.lang.Integer"
                        resultType="com.trace.app.framework.toolsmodel.LogResult">
                        SELECT * FROM t_logs WHERE company_sid = #{companySid}
                </select>
    </mapper>
    
    <!--
    #{}:如果传入的是pojo类型,那么#{}中的变量名称必须是pojo中对应的属性.属性.属性.....
    -->
    

    相关文章

      网友评论

        本文标题:SpringMVC整合Mybatis具体实现

        本文链接:https://www.haomeiwen.com/subject/ojiqsftx.html