Spring——Spring整合MyBatis

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
云数据库 RDS MySQL,高可用系列 2核4GB
简介: Spring——Spring整合MyBatis

文章目录:

1.写在前面

2.实现步骤

2.1 项目的大体框架 

2.2 使用Navicat在数据库中创建一张表student2

2.3 pom.xml文件中加入maven依赖

2.4 编写实体类Student

2.5 编写StudentDao接口和对应的mapper映射文件

2.6 编写MyBatis主配置文件

2.7 编写service接口和相应的实现类(目的是通过service调用dao接口中的方法)

2.8 编写Spring配置文件

2.8.1 加载外部属性配置文件 

2.8.2 声明数据源

2.8.3 注册SqlSessionFactoryBean

2.8.4 定义Mapper扫描配置器MapperScannerConfigurer

2.8.5 Service中注入相关的接口名

2.9 编写测试方法

2.9.1 测试方法1

2.9.2 测试方法2

2.9.3 测试方法3

3.写在结尾


1.写在前面


MyBatisSpring 进行整合,主要解决的问题就是将 SqlSessionFactory 对象交由 Spring 来管理。所以,该整合,只需要将 SqlSessionFactory 的对象生成器 SqlSessionFactoryBean 注册在Spring 容器中,再将其注入给 Dao 的实现类即可完成整合。实现 Spring MyBatis 的整合常用的方式:扫描的 Mapper 动态代理 Spring 像插线板一样,mybatis框架是插头,可以容易的组合到一起。插线板 spring 插上 mybatis,两个框架就是一个整体。 

使用mybatis,需要创建mybatis框架中的某些对象,使用这些对象,就可以使用mybatis提供的功能了。

对于mybatis执行sql语句,需要用到的对象有:

1.    SqlSessionFactory对象,只有创建了SqlSessionFactory对象,才能调用openSession()方法得到SqlSession对象。

2.    dao接口的代理对象,例如StudentDao接口,需要的代理对象为:SqlSeesion.getMapper(StudentDao.class)

3.    数据源DataSource对象,使用一个更强大、功能更多的连接池对象代替mybatis自己的PooledDataSource

2.实现步骤


2.1 项目的大体框架

这里先给出spring整合mybatis之后,整个项目的架构图。 

2.2 使用Navicat在数据库中创建一张表student2


其中 id 字段为主键,同时设置了自动增长。

2.3 pom.xml文件中加入maven依赖

<!-- spring依赖 -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.2.5.RELEASE</version>
</dependency>
<!-- spring事务依赖 -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>5.2.5.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>5.2.5.RELEASE</version>
</dependency>
<!-- mybatis依赖 -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.1</version>
</dependency>
<!-- mybatis和spring集成依赖 -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>1.3.1</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.9</version>
</dependency>
<!-- 阿里的连接池 -->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.1.12</version>
</dependency>
<!-- 单元测试 -->
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>
<build>
    <resources>
      <resource>
        <directory>src/main/java</directory> <!--所在的目录-->
        <includes> <!--包括目录下的.properties,.xml 文件都会扫描到-->
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
 </build>

2.4 编写实体类Student

package com.bjpowernode.entity;
/**
 *
 */
public class Student {
    private Integer id;
    private String name;
    private Integer age;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


2.5 编写StudentDao接口和对应的mapper映射文件

package com.bjpowernode.dao;
import com.bjpowernode.entity.Student;
import java.util.List;
/**
 *
 */
public interface StudentDao {
    int insertStudent(Student student);
    List<Student> selectStudent();
}
<?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.bjpowernode.dao.StudentDao">
    <!-- 使用insert、update、delete、select标签编写sql语句 -->
    <insert id="insertStudent">
        insert into student2(name,age) values(#{name},#{age})
    </insert>
    <select id="selectStudent" resultType="com.bjpowernode.entity.Student">
        select id,name,age from student2
    </select>
</mapper>

2.6 编写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>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <mappers>
<!--        <mapper resource="com/bjpowernode/dao/StudentDao.xml"/>-->
        <!-- 将dao包下的所有mapper文件全部扫描 -->
        <package name="com.bjpowernode.dao"/>
    </mappers>
</configuration>


2.7 编写service接口和相应的实现类(目的是通过service调用dao接口中的方法)

package com.bjpowernode.service;
import com.bjpowernode.entity.Student;
import java.util.List;
/**
 *
 */
public interface StudentService {
    int addStudent(Student student);
    List<Student> queryStudent();
}
package com.bjpowernode.service.impl;
import com.bjpowernode.dao.StudentDao;
import com.bjpowernode.entity.Student;
import com.bjpowernode.service.StudentService;
import java.util.List;
public class StudentServiceImpl implements StudentService {
    private StudentDao studentDao;
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
    @Override
    public int addStudent(Student student) {
        int rows=studentDao.insertStudent(student);
        return rows;
    }
    @Override
    public List<Student> queryStudent() {
        List<Student> students=studentDao.selectStudent();
        return students;
    }
}

2.8 编写Spring配置文件

这里使用阿里的连接池、以及外部属性配置文件来读取数据库连接的相关信息。

先给出外部属性配置文件:jdbc.properties

jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&amp;characterEncoding=utf-8
jdbc.username=root
jdbc.password=12345678

2.8.1 加载外部属性配置文件

<!-- 加载外部属性配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>

2.8.2 声明数据源

<!-- 声明数据源DataSource -->
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

2.8.3 注册SqlSessionFactoryBean

<!-- 声明SqlSessionFactoryBean,在这个类的内部,创建SqlSessionFactory对象,之后就可以获取SqlSession对象 -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 指定数据源 -->
    <property name="dataSource" ref="myDataSource"/>
    <!-- 指定mybatis主配置文件 -->
    <property name="configLocation" value="classpath:mybatis.xml"/>
</bean>

2.8.4 定义Mapper扫描配置器MapperScannerConfigurer

<!-- 声明MapperScannerConfigurer -->
<!--
     MapperScannerConfigurer作用:
       循环basePackage所表示的包,把包中的每个接口都找到,调用SqlSession.getMapper(XXXDao.class)
       把每个dao接口都创建出对应的dao代理对象,将dao代理对象放在容器中
       对于StudentDao接口,其代理对象为 studentDao
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!-- 指定SqlSessionFactory对象的名称 -->
    <property name="sqlSessionFactoryBeanName" value="factory"/>
    <!-- 指定基本包,dao接口所在的包名 -->
    <property name="basePackage" value="com.bjpowernode.dao"/>
</bean>

2.8.5 Service中注入相关的接口名

<!-- 声明service -->
<bean id="studentService" class="com.bjpowernode.service.impl.StudentServiceImpl">
    <property name="studentDao" ref="studentDao"/>
</bean>

2.9 编写测试方法

2.9.1 测试方法1

    @Test
    public void test01() {
        String config="applicationContext.xml";
        ApplicationContext ctx=new ClassPathXmlApplicationContext(config);
        StudentDao studentDao= (StudentDao) ctx.getBean("studentDao");
        Student student=new Student();
        student.setName("李四");
        student.setAge(20);
        studentDao.insertStudent(student);
    }


2.9.2 测试方法2

    @Test
    public void test02() {
        String config="applicationContext.xml";
        ApplicationContext ctx=new ClassPathXmlApplicationContext(config);
        StudentService service= (StudentService) ctx.getBean("studentService");
        Student student=new Student();
        student.setName("张三");
        student.setAge(25);
        service.addStudent(student);
    }

2.9.3 测试方法3

    @Test
    public void test03() {
        String config="applicationContext.xml";
        ApplicationContext ctx=new ClassPathXmlApplicationContext(config);
        StudentService service= (StudentService) ctx.getBean("studentService");
        List<Student> students=service.queryStudent();
        for (Student stu : students) {
            System.out.println("stu = " + stu);
        }
    }


3.写在结尾


Spring整合MyBatis的总体步骤可以总结为以下几点:👇👇👇


spring集成mybatis,实现步骤:
1.使用mysql数据库,创建学生表student2(id int 自动增长,name varchar(30),age int)
2.创建maven项目
3.加入依赖
  spring依赖、mybatis依赖、mysql驱动、junit单元测试
  spring-mybatis依赖(mybatis网站上提供的,用来在spring项目中,创建mybatis对象)
  spring有关事务的依赖
  mybatis和spring整合的时候,事务是自动提交的。
4.创建实体类Student
5.创建dao接口和mapper文件,编写其中的sql语句
6.编写mybatis主配置文件
7.创建service接口和它的实现类
8.创建spring的配置文件
  1) 声明数据源DataSource,使用阿里的Druid连接池
  2) 声明SqlSessionFactoryBean类,在这个类的内部创建SqlSessionFactory对象
  3) 声明MapperScannerConfigurer类,在这个类的内部创建dao代理对象,创建的对象放在spring容器中
  4) 声明service对象,把3)中的dao赋值给service对象属性
9.测试dao访问数据库


相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
8月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
453 0
|
5月前
|
Java 数据库连接 数据库
Spring boot 使用mybatis generator 自动生成代码插件
本文介绍了在Spring Boot项目中使用MyBatis Generator插件自动生成代码的详细步骤。首先创建一个新的Spring Boot项目,接着引入MyBatis Generator插件并配置`pom.xml`文件。然后删除默认的`application.properties`文件,创建`application.yml`进行相关配置,如设置Mapper路径和实体类包名。重点在于配置`generatorConfig.xml`文件,包括数据库驱动、连接信息、生成模型、映射文件及DAO的包名和位置。最后通过IDE配置运行插件生成代码,并在主类添加`@MapperScan`注解完成整合
1010 1
Spring boot 使用mybatis generator 自动生成代码插件
|
5月前
|
Java 数据库连接 API
Java 对象模型现代化实践 基于 Spring Boot 与 MyBatis Plus 的实现方案深度解析
本文介绍了基于Spring Boot与MyBatis-Plus的Java对象模型现代化实践方案。采用Spring Boot 3.1.2作为基础框架,结合MyBatis-Plus 3.5.3.1进行数据访问层实现,使用Lombok简化PO对象,MapStruct处理对象转换。文章详细讲解了数据库设计、PO对象实现、DAO层构建、业务逻辑封装以及DTO/VO转换等核心环节,提供了一个完整的现代化Java对象模型实现案例。通过分层设计和对象转换,实现了业务逻辑与数据访问的解耦,提高了代码的可维护性和扩展性。
227 1
|
4月前
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
156 0
|
5月前
|
SQL Java 数据库
解决Java Spring Boot应用中MyBatis-Plus查询问题的策略。
保持技能更新是侦探的重要素质。定期回顾最佳实践和新技术。比如,定期查看MyBatis-Plus的更新和社区的最佳做法,这样才能不断提升查询效率和性能。
235 1
|
10月前
|
SQL Java 数据库连接
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
544 29
|
8月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
685 0
|
8月前
|
Java 数据库连接 数据库
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
1101 0
|
10月前
|
SQL JavaScript Java
Spring Boot 3 整合 Mybatis-Plus 实现数据权限控制
本文介绍了如何在Spring Boot 3中整合MyBatis-Plus实现数据权限控制,通过使用MyBatis-Plus提供的`DataPermissionInterceptor`插件,在不破坏原有代码结构的基础上实现了细粒度的数据访问控制。文中详细描述了自定义注解`DataScope`的使用方法、`DataPermissionHandler`的具体实现逻辑,以及根据用户的不同角色和部门动态添加SQL片段来限制查询结果。此外,还展示了基于Spring Boot 3和Vue 3构建的前后端分离快速开发框架的实际应用案例,包括项目的核心功能模块如用户管理、角色管理等,并提供Gitee上的开源仓库
2030 11
|
10月前
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
459 2
下一篇
oss云网关配置