MyBatis用法——从纯MyBatis到MyBatis-Spring

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BuquTianya/article/details/78941650

概述

引用一句《增广贤文》的句子:“昔时贤文,诲汝谆谆。集韵增广,多见多闻。观今宜鉴古,无古不成今。”希望能够尽快打通自己的任督二脉,跨入新的境界,共勉!

计算机编程有一个很有趣的现象,技术迭代更新速度特别特别快,总是让我们这些技术宅们应接不暇。总感觉怎么学都赶不上技术迭代更新的速度,抓不住时间的尾巴。无奈至极,悲情伤感,甚至消沉乏味。

迭代更新的背后藏着的一个现象需要引起特别的注意,如果没有注意到那么所有的新技术都容易让人摸不到头脑,只是学到了用法和表皮。

这个现象就是:大多数的技术都是在做更高层的封装,朝更便利的发展。大多的技术都是从原来的技术上发展起来的,都是以以前的技术做基础的。比如,要了解elastic-job,那么你最好先了解quartz,想了解quartz,最好先了解java的定时器;比如,想了解kafka或者rocketmq,最好先了解activemq;比如,想了解spring cloud,最好先了解spring boot, 想了解spring boot,最好先了解spring;比如,想了解spring mvc,最好先了解jsp,想了解jsp,最好先先了解servlet;比如,想了解spring mybatis,最好先了解mybatis,要想了解mybatis,最好先了解jdbc。

总结起来就是,每当我们对新技术一脸茫然时,很大的可能性就是我们对新技术的本源还不了解,需要补充相关方面的知识。当这些知识补全之后,对新技术就会豁然明了。

接下来的部分只涉及到最简单的使用,尚不涉及复杂映射、分页、排序、事务等内容。

纯MyBatis的使用

MyBatis的4大关键类

SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession、映射器(Mapper)是MyBatis的四大关键类。

SqlSessionFactoryBuilder作用是加载配置信息和属性信息创建一个SqlSessionFactory。有了SqlSessionFactory我们就可以创建SqlSession,就相当于有了和数据库的连接(类比于jdbc的Connection)。SqlSession可以执行Mapper中的任何sql映射器,执行sql,完成和数据库的交互。

MyBatis配置文件

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

<typeAliases>
  <typeAlias alias="Blog" type="com.dangdang.model.Blog"/>
</typeAliases>

  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
      </dataSource>
    </environment>
  </environments>

  <mappers>
    <mapper resource="com/dangdang/mapper/BlogMapper.xml"/>
  </mappers>
</configuration>

映射器(Mapper)

<!-- BlocMapper.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.dangdang.mapper.BlogMapper">

  <select id="selectBlog" resultType="Blog">
    select * from blog where id = #{id}
  </select>
</mapper>

Model类

package com.dangdang.model;

import java.util.Date;

public class Blog {
    private long id;
    private String content;
    private String postuser;
    private Date postdate;

    //...getter and setter ....

    public String toString() {
        return "id:" + this.id + " content:" + this.content + " user:" + this.postuser + " time:" + this.postdate;
    }
}

调用MyBatis


public class App 
{
    public static void main( String[] args ) throws IOException
    {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            SqlSession session = sqlSessionFactory.openSession();
            try {
              Blog blog = (Blog) session.selectOne("com.dangdang.mapper.BlogMapper.selectBlog", 1);
              System.out.println(blog);
            } finally {
              session.close();
            }
    }
}

类纯MyBatis的Mybatis-Spring用法

上一节中的Model、Mapper.xml、都不变,仅需要增加spring的xml配置文件,修改mybatis-config.xml配置文件即可。

spring 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:tx="http://www.springframework.org/schema/tx"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
                http://www.springframework.org/schema/context  
                 http://www.springframework.org/schema/context/spring-context-3.2.xsd  
                http://www.springframework.org/schema/tx   
                http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">  

    <!-- 加载配置JDBC文件 -->  
    <context:property-placeholder location="classpath:mybatis-config.properties" />  
    <!-- 数据源 -->  
    <bean id="dataSource"  
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
        <property name="driverClassName">  
            <value>${jdbc.driver}</value>  
        </property>  
        <property name="url">  
            <value>${jdbc.url}</value>  
        </property>  
        <property name="username">  
            <value>${jdbc.username}</value>  
        </property>  
        <property name="password">  
            <value>${jdbc.password}</value>  
        </property>  
    </bean>  

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />   
        <property name="mapperLocations" value="classpath:com/dangdang/mapper/BlogMapper.xml" /> 
        <property name="configLocation" value="classpath:mybatis-config.xml"></property> 
    </bean>  
</beans>  

修改后的mybatis-config.xml

仅需要删除连接和mapper相关的配置就可以了,因为这些配置转移到了spirng的xml配置文件里面。如果不需要特殊配置 <settings><typeAliases> 的话,这个配置文件可以删掉不要。

<?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>
<typeAliases>
  <typeAlias alias="Blog" type="com.dangdang.model.Blog"/>
</typeAliases>

</configuration>

调用MyBatis

public class App 
{
    public static void main( String[] args )
    {
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("application-context.xml");
        SqlSessionFactory factory = (SqlSessionFactory)ac.getBean("sqlSessionFactory");

        SqlSession session = factory.openSession();
            try {
              Blog blog = (Blog) session.selectOne("com.dangdang.mapper.BlogMapper.selectBlog", 1);
              System.out.println(blog);
            } finally {
              session.close();
            }
    }
}

MyBatis-Spring的最常见用法

当然一般来说我们不会像上边一节那样,直接使用SqlSessionFactory去执行数据库请求,因为MyBatis-Spring提供了更便利的用法。

他可以直接给我们生成dao实例对象,从而可以直接调用dao对象的相关方法。从而,不需要关系连接的关闭,更加直接、简便。

我们需要增加一个和BlogMapper对应的dao接口,需要修改spring的xml配置文件,增加映射器自动扫描。另外,mapper.xml的namespace值需要和对应的Dao.class的完全限定名一致。

增加IBlogManager接口

package com.dangdang.dao;

import com.dangdang.model.Blog;

public interface IBlogManager {
    Blog selectBlog(long id);
}

修改spring的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:tx="http://www.springframework.org/schema/tx"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
                http://www.springframework.org/schema/context  
                 http://www.springframework.org/schema/context/spring-context-3.2.xsd  
                http://www.springframework.org/schema/tx   
                http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">  

    <!-- 加载配置JDBC文件 -->  
    <context:property-placeholder location="classpath:mybatis-config.properties" />  
    <!-- 数据源 -->  
    <bean id="dataSource"  
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
        <property name="driverClassName">  
            <value>${jdbc.driver}</value>  
        </property>  
        <property name="url">  
            <value>${jdbc.url}</value>  
        </property>  
        <property name="username">  
            <value>${jdbc.username}</value>  
        </property>  
        <property name="password">  
            <value>${jdbc.password}</value>  
        </property>  
    </bean>  

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />   
        <property name="mapperLocations" value="classpath:com/dangdang/mapper/BlogMapper.xml" /> 
        <property name="configLocation" value="classpath:mybatis-config.xml"></property> 
    </bean>  

    <bean id="MapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.dangdang.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> 
    </bean>  
</beans>  

修改mapper.xml的namespace值

<?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需要和dao的类限定名一致 -->
<mapper namespace="com.dangdang.dao.IBlogManager">

  <select id="selectBlog" resultType="Blog">
    select * from blog where id = #{id}
  </select>
</mapper>

调用MyBatis

public class App 
{
    public static void main( String[] args )
    {
             ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("application-context.xml");
             IBlogManager blogManager = ac.getBean(IBlogManager.class);

              Blog blog = blogManager.selectBlog(1);
              System.out.println(blog);
    }
}

总结

几种方式走下来,总体感觉没有太大的差异,MyBatis-Spring只是结合了spring的注入、动态代理优势之后,免去了我们一些调用Mybatis时的代码,免去了SqlSessionFactoryBuilder的配置,把MyBatis的配置文件格式进行修改,融入到了spring的配置格式之中。

相关代码见:http://download.csdn.net/download/buqutianya/10182224

猜你喜欢

转载自blog.csdn.net/BuquTianya/article/details/78941650