最新Spring整合MyBatis详解教程

最新Spring整合MyBatis详解教程目录1.导入相关jar包1.junit2.mybatis3.mysql4.spring相关5.aop织入6.mybatis-spring7.lombok(选用)2.回顾:建立一个Mybatis程序1.IDEA连接数据库2.编写MyBatis核心配置文件3.创建数据库表对应实体类4.编写Mapper接口5.编写Mapper.xml配置文件6.编写测试类7.给Mapper.xml添加注册8.测试运行3.spring整合方式一:1.引入spring配置文件2.使用Sprin

大家好,又见面了,我是你们的朋友全栈君。


image-20200811201331833

mybatis-spring官方文档:http://mybatis.org/spring/zh/index.html

首先新建一个空的maven项目

1、导入相关jar包


1. junit

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
    <scope>test</scope>
</dependency>

2. mybatis

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

3. mysql

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

4. spring相关

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>
<!--Spring操作数据库,还需要spring-jdbc-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.1.3.RELEASE</version>
</dependency>

5. aop织入

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

6. mybatis-spring

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

7. lombok(选用)

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
</dependency>

最后为了防止maven配置文件无法被导出或生效,加入以下代码

<!--在build中配置resources,防止我们资源导出失败的问题-->
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

2、回顾:建立一个Mybatis程序

更详细过程可以看我之前的博客第一个MyBatis程序


1. IDEA连接数据库

大家连接自己的数据库即可,这里的实验表格为
image-20200811181559385

2. 编写MyBatis核心配置文件

image-20200811181900880

<?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>
    <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?useSSH=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="200024"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

3. 创建数据库表对应实体类

image-20200811181927962

package pojo;

import lombok.Data;

@Data
public class User { 
   
    private int id;
    private String name;
    private String pwd;
}

4. 编写Mapper接口

image-20200811182020272

package mapper;

import pojo.User;

import java.util.List;

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

5. 编写Mapper.xml配置文件

image-20200811182204453

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper.UserMapper">
    <select id="getUser" resultType="pojo.User">
        select * from mybatis.user
    </select>
</mapper>

6. 编写测试类

image-20200811182242082

public class Test { 
   
    @org.junit.Test
    public void test() throws IOException { 
   
        String resource = "mybatis-config.xml";
        InputStream in = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = sessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.getUser();
        for (User user : users) { 
   
            System.out.println(user);
        }
    }
}

7. 给Mapper.xml添加注册

在核心配置文件mybatis-config.xml中加入以下代码

<mappers>
    <mapper class="mapper.UserMapper"/>
</mappers>

8. 测试运行

image-20200811194703348

到此,mybatis程序的创建已成功,接下来将进行修改,整合spring

3、spring整合:方式一

通过SqlSessionTemplate创建SqlSession


接下来将在上述实验环境下进行修改

1. 引入spring配置文件

resource目录下新建spring-dao.xml
image-20200811183008850

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

</beans>

2. 使用Spring的数据源替换MyBatis的数据源配置

spring配置文件中加入以下代码,配置数据源信息

<!--DataSource:使用Spring的数据源替换MyBatis的配置-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSH=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
    <property name="username" value="root"/>
    <property name="password" value="200024"/>
</bean>

此时,就可以删除mybatis核心配置文件mybatis-config.xml中的数据源配置
image-20200811184444369

3. 通过spring创建sqlSessionFactory

  • MyBatis 中,是通过 SqlSessionFactoryBuilder 来创建 SqlSessionFactory
  • 而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean 来创建

spring配置文件中加入以下代码,创建sqlSessionFactory

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

唯一的必要属性:用于 JDBC 的 DataSource,注入上述创建好的数据源

还可以配置其他属性,完全取代mybatis-config.xml中的配置
image-20200811185806672
这里加入两个属性配置

  • configLocation:指定mybatis的xml配置文件路径
  • mapperLocations:注册Mapper.xm映射器
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!--绑定mybatis配置文件-->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <!--注册Mapper.xm映射器-->
    <property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>

这里,我们在spring配置文件中注册了Mapper.xml,就可以删除mybatis-config.xml中的Mapper.xml的注册
image-20200811185526572

4. 创建sqlSession对象

  • 在mybatis中,SqlSession 提供了在数据库执行 SQL 命令所需的所有方法

  • 而在spring-mybatis,没有SqlSession了,而是SqlSessionTemplate,这两个是同一个东西


spring配置文件中加入以下代码,创建sqlSession

  • 这里使用上述创建好的sqlSessionFactory 作为构造方法的参数来创建 SqlSessionTemplate 对象。
<!--SqlSessionTemplate:就是我们使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <!--只能使用构造器进行注入,因为没有set方法-->
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

5. 新建接口实现类

上一步我们创建了sqlSession对象,此时需要创建一个类来使用sqlSession

image-20200811191543680

在该类中添加一个 SqlSession 属性,并添加 set方法 用于后续sqlSession的注入

public class UserMapperImpl implements UserMapper { 
   
    //原来所有操作都通过SqlSession来执行,现在都是SqlSessionTemplate
    private SqlSessionTemplate sqlSession;

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

    public List<User> getUser() { 
   
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.getUser();
    }
}

6. 创建实现类对象

利用spring创建上述接口实现类对象,取名为userMapper,并注入上述创建好的sqlSession对象

<bean id="userMapper" class="mapper.UserMapperImpl">
    <property name="sqlSession" ref="sqlSession"/>
</bean>

7. 修改测试类

此时,无需像先前一样创建sqlSessionFactory和sqlSession,我们只需获得创建好的实体类对象UserMapper,然后调用该对象的方法即可

public class Test { 
   
    @org.junit.Test
    public void test() throws IOException { 
   
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapperImpl userMapper = (UserMapperImpl) context.getBean("userMapper");
        List<User> users = userMapper.getUser();
        for (User user : users) { 
   
            System.out.println(user);
        }
    }
}

8. 运行测试

image-20200811194703348

运行成功!!!

4、spring整合:方式二

通过SqlSessionDaoSupport获得Sqlsession


接下来将在上述实验环境下进行修改

1. 新建接口实现类

新建一个接口实现类,继承SqlSessionDaoSupport类,直接可以获得SqlSession对象
image-20200811205114097

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

2. 创建接口实现类对象

通过Spring来创建

spring配置文件中创建上述实体类对象userMapper2,并设置sqlSessionFactory属性为上述创建好的sqlSessionFactory

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

3. 修改测试类

同样,无需像先前一样创建sqlSessionFactory和sqlSession,我们只需获得创建好的实体类对象UserMapper2,然后调用该对象的方法即可

public class Test { 
   
    @org.junit.Test
    public void test() throws IOException { 
   
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapperImpl2 userMapper = (UserMapperImpl2) context.getBean("userMapper2");
        List<User> users = userMapper.getUser();
        for (User user : users) { 
   
            System.out.println(user);
        }
    }
}

4. 测试运行

image-20200811210202877

成功运行!!


THE END…

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/130396.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • NVIC设置

    NVIC设置NVIC终端优先级分组(NestVectorInterruptControl嵌套式向量中断控制器)CM4内核支持256个中断,其中包含了16个内核中断和240个外部中断,并且具有256级的可编程中断设置。STM32F4只是使用了其中的一部分。STM32F40xx/STM32F41xx的92个中断里面,包括10个内核中断,82个可屏蔽中断(常用)“`分组寄存器SCB->…

    2022年5月28日
    90
  • Yii2 Call to a member function validateCsrfToken() on string

    Yii2 Call to a member function validateCsrfToken() on string

    2022年2月18日
    37
  • Vue源码–解读vue响应式原理

    Vue源码–解读vue响应式原理原文链接:https://geniuspeng.github.io/2018/01/05/vue-reactivity/Vue的官方说明里有深入响应式原理这一节。在此官方也提到过:当你把一个普通的JavaScript对象传给Vue实例的data选项,Vue将遍历此对象所有的属性,并使用Object.defineProperty把这些属性全部转为getter/setter。Obj…

    2022年6月6日
    25
  • html script 换行,JavaScript中怎么换行

    html script 换行,JavaScript中怎么换行js中换行的方法:1、使用【\n】换行符,代码为【alert(“第一行\n第二行”)】;2、使用【\r】换行符,代码为【alert(“第一行\r第二行”)】;3、使用HTML的【】标签。本教程操作环境:windows7系统、javascript1.8.5版,DELLG3电脑。JavaScript中换行的方法:方法1:使用换行符1、\n换行符在JavaScript中我们可以直接在要换行的地方使用\…

    2022年10月24日
    1
  • equals和==的区别

    equals和==的区别

    2021年9月12日
    55
  • 层叠样式表——CSS

    层叠样式表——CSS层叠样式表——CSS

    2022年4月24日
    44

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号