12、Spring整合Mybatis

12.1、步骤

  1. 导入相关jar包

junit

<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.12</version>
</dependency>

mybatis

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.5.2</version>
</dependency>

mysql-connector-java

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.47</version>
</dependency>

spring相关

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.1.10.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>5.1.10.RELEASE</version>
</dependency>

AOP织入器

<dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.9.4</version>
</dependency>

mybatis-spring整合包【重点】

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis-spring</artifactId>
   <version>2.0.2</version>
</dependency>

配置Maven讲台资源过滤问题

<build>
   <resources>
       <resource>
           <directory>src/main/java</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>true</filtering>
       </resource>
   </resources>
</build>
  1. 编写配置文件

  2. 测试

12.2、回忆Mybatis

编写pojo类

public class User {
    private int id;
    private String name;
    private String pwd;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

实现mybatis的配置文件

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- configuration核心配置文件 -->
<configuration>


    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>

</configuration>

UserMapper接口编写

public interface UserMapper {
    List<User> selectUser();
}

接口对应的Mapper文件

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chen.mapper.UserMapper">
    <select id="selectUser" resultType="com.chen.pojo.User">
        select * from user;
    </select>
</mapper>

测试类

    @Test
    public void test01(){
        String resource = "mybatis-config.xml";
        try {
            InputStream in = Resources.getResourceAsStream(resource);
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
            SqlSession session = sessionFactory.openSession();
            UserMapper mapper = session.getMapper(UserMapper.class);
            List<User> userList = mapper.selectUser();
            for (User user : userList) {
                System.out.println(user);
            }
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

12.3、Mybatis-Spring学习

引入Spring之前需要了解mybatis-spring包中的一些重要类;
http://www.mybatis.org/spring/zh/index.html

什么是Mybatis-Spring?

Mybatis-Spring会帮助你将Mybatis代码无缝的整合到Spring中。

知识基础

在开始使用mybatis-spring之前,你需要先熟悉Spring和Mybatis这两个框架还有它们的术语。

Mybatis-Spring需要以下版本

Mybatis-SpringMybatisSpring框架Srping BatchJava
2.03.5+5.0+4.0+Java 8+
1.33.4+3.2.2+2.1+Java 6+

如果使用Maven作为构建工具,仅需要在pom.xml中加入以下代码即可:

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis-spring</artifactId>
   <version>2.0.2</version>
</dependency>

要和Spring一起使用Mybatis,需要在Spring应用上下文中定义至少两样东西:一个SqlSessionFactory和至少一个数据映射器

在Mybatis-Spring中,可使用SqlSessionFactoryBean来创建SqlSessionFactory。需要配置这个工厂bena,只需要把下面代码放在Spring的XML配置文件中:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 <property name="dataSource" ref="dataSource" />
</bean>

注意:SqlSseeionFactory需要一个DataSource(数据源)。这可以是任意的DataSource,只需要和配置其他Mybatis数据库连接一样配置它就可以了。

在基础的Mybatis用法中,是通过SqlSessionFactoryBuilder来创建SqlSessionFactory的。而在Mybatis-Spring中,则使用SqlSessionFactoryBean来创建。

在Mybatis中,你可以使用SqlSessionFactory来创建SqlSession,一旦你获得一个session之后,你可以用它来执行映射了的语句,提交或回滚连接,最后,当你不需要它的时候,你可以关闭session。

SqlSessionFactory有一个唯一的必要属性:用于JDBC的DataSource。这可以是任意的DataSource对象,它的配置方法和其它Mybatis数据库连接是一样的。

一个常用的属性是configLocation,它用来指定Mybatis的XML配置文件路径。它在需要修改Mybatis的基础非常有用。通常,基础配置指令是< settings >或< typeAliases >元素。

需要注意的是,这个配置文件不需要是一个完整的Mybatsi配置。确切地说,任何环境配置(< environments >),数据源(< DataSource >)和MyBatis的任务管理器(< transactionManager >)都会被忽略。SqlSessionFactoryBean会创建它自有的MyBatis环境配置(Environment),并按要求设置自定义环境的值。

SqlSessionTemplate是MyBatis-Spring的核心。作为SqlSession的一个实现类,这意味着可以使用它无缝代替你代码中已经在使用的SqlSession。

模板可以参与到Spring的事务管理中,并且由于其是线程安全的,可以供多个映射器类使用,你应该总是用SqlSessionTemplate来替换Mybatis默认的DefaultSqlSession实现。在同一应用程序中的不同类之间混杂使用可能会引起数据一致性的问题。

可以使用SqSessionFactory作为构造方法的参数来创建SqlSessionTemplated对象。

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
 <constructor-arg index="0" ref="sqlSessionFactory" />
</bean>

现在,这个bean就可以直接注入到你的DAO bean中了。你需要在你的bean中添加一个SqlSession属性,就像下面这样:

public class UserDaoImpl implements UserDao {

 private SqlSession sqlSession;

 public void setSqlSession(SqlSession sqlSession) {
   this.sqlSession = sqlSession;
}

 public User getUser(String userId) {
   return sqlSession.getMapper...;
}
}

按下面这样,注入SqlSessionTemplate

<bean id="userDao" class="org.mybatis.spring.sample.dao.UserDaoImpl">
 <property name="sqlSession" ref="sqlSession" />
</bean>

12.4、整合实现一

  1. 引入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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>
  1. 配置数据源替换mybatis的数据源
    <!-- DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
    我们这里使用Spring的JDBC
    -->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
  1. 配置SqlSessionFactory,关联MyBatis
    <!-- sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--引用数据源-->
        <property name="dataSource" ref="datasource"/>
        <!-- 绑定Mybatis配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--mappers映射配置文件-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
     </bean>
  1. 注册sqlSessionTemplate,关联sqlSessionFactory
    <!-- SqlSessionTemplate就是sqlSession -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!-- 只能用构造器注入sqlSessionFactory,因为它没有set方法 -->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
  1. 增加Dao接口的实现类:私有化sqlSessionTemplate
public class UserMapperImpl implements UserMapper{

    //原来我们的所有操作都使用sqlSession来执行,现在都是使用SqlSessionTemplate
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.selectUser();
        return userList;
    }
}
  1. 注册bean实现
    <bean id="userMapper" class="com.chen.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
  1. 测试
    @Test
    public void test01(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        List<User> userList = userMapper.selectUser();
        for (User user : userList) {
            System.out.println(user);
        }
    }

结果成功输出!现在我们的Mybatis配置文件的状态!发现都可以被Spring整合!

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- configuration核心配置文件 -->
<configuration>

    <typeAliases>
        <package name="com.chen.pojo"/>
    </typeAliases>

</configuration>

12.5、整合实现二

mybatis-spring1.2.3版以上的才有这个 .

官方文档截图 :

dao继承Support类 , 直接利用 getSqlSession() 获得 , 然后直接注入SqlSessionFactory . 比起方式1 , 不需要管理SqlSessionTemplate , 而且对事务的支持更加友好 . 可跟踪源码查看
在这里插入图片描述
测试:
1.UeseMapperImpl2.java

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    public List<User> selectUser() {
        SqlSession sqlSession = getSqlSession();
        return sqlSession.getMapper(UserMapper.class).selectUser();
    }
}

2.注册bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
    我们这里使用Spring的JDBC
    -->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <!-- sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--引用数据源-->
        <property name="dataSource" ref="datasource"/>
        <!-- 绑定Mybatis配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--mappers映射配置文件-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
     </bean>
     
	<!-- 使用SqlSessionDaoSupport的getSqlSseeion,可以获取一个sqlSession,所以可以不用写SqlSessionTemplate的bean -->

    <bean id="userMapper2" class="com.chen.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

</beans>

3.测试

    @Test
    public void test02(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
        List<User> userList = userMapper.selectUser();
        for (User user : userList) {
            System.out.println(user);
        }
    }

学习视频链接:https://www.bilibili.com/video/BV1WE411d7Dv?p=24

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值