SpringBoot——SpringBoot集成MyBatis

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: SpringBoot——SpringBoot集成MyBatis

文章目录:


1.使用@Mapper注解集成MyBatis

1.1 前期准备工作

1.2 pom.xml

1.3 GeneratorMapper.xml(配置MyBatis逆向工程核心文件)

1.3.1 Student实体类

1.3.2 StudentMapperStudentMapper.xml

1.4 servicecontroller

1.5 SpringBoot核心配置文件、SpringBoot项目启动入口类

2.使用@MapperScan注解集成MyBatis(将mapper接口和映射文件分开)

2.1 mapper接口、对应的mapper映射文件

2.2 启动入口类测试


1.使用@Mapper注解集成MyBatis


1.1 前期准备工作


首先我们需要准备一个数据库、一张表,用作测试。

CREATE DATABASE springboot;
USE springboot;
DROP TABLE IF EXISTS t_student;
CREATE TABLE t_student (
    id int(10) NOT NULL AUTO_INCREMENT,
    name varchar(20) NULL ,
    age int(10) NULL ,
    PRIMARY KEY (id)
)ENGINE = INNODB DEFAULT CHARSET = utf8;
INSERT INTO t_student(name,age) VALUES ('zhangsan',25);
INSERT INTO t_student(name,age) VALUES ('lisi',28);
INSERT INTO t_student(name,age) VALUES ('wangwu',23);
INSERT INTO t_student(name,age) VALUES ('Tom',21);
INSERT INTO t_student(name,age) VALUES ('Jack',18);
INSERT INTO t_student(name,age) VALUES ('Lucy',27);
INSERT INTO t_student(name,age) VALUES ('xiaosong',21);


1.2 pom.xml

由于集成的是MyBatis,肯定要使用数据库,所以需要添加的两个依赖项就是 mysql驱动、mybatis集成springboot的起步依赖。

同时在 build 标签下,手动指定文件夹为resources,以及添加mybatis代码自动生成插件。

<dependencies>
        <!-- SpringBoot框架web项目起步依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!-- MyBatis整合SpringBoot框架的起步依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
    </dependencies>
    <build>
        <!-- 手动指定文件夹为resources -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <!--mybatis 代码自动生成插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <configuration>
                    <!--配置文件的位置-->
                    <configurationFile>GeneratorMapper.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
            <!-- SpringBoot项目编译打包的插件 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

1.3 GeneratorMapper.xml(配置MyBatis逆向工程核心文件)


由于在未来的真实项目开发过程中,可能会涉及到很多张表、很多的dao接口、dao接口对应的mapper文件,那么这些文件我们一一编写就会显得比较麻烦,而且写来写去没什么意义,所以这里我们采用 MyBatis逆向工程来直接生成对应的实体类daomapper

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
        <!-- 指定连接数据库的 JDBC 驱动包所在位置,指定到你本机的完整路径 -->
        <classPathEntry location="E:\mysql-connector-java-5.1.9.jar"/>
        <!-- 配置 table 表信息内容体,targetRuntime 指定采用 MyBatis3 的版本 -->
        <context id="tables" targetRuntime="MyBatis3">
            <!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 -->
            <commentGenerator>
                <property name="suppressAllComments" value="true"/>
            </commentGenerator>
            <!-- 配置数据库连接信息 -->
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                            connectionURL="jdbc:mysql://localhost:3306/springboot"
                            userId="root"
                            password="12345678">
            </jdbcConnection>
            <!-- 生成 entity 类,targetPackage 指定 entity 类的包名, targetProject指定生成的 entity 放在 IDEA 的哪个工程下面-->
            <javaModelGenerator targetPackage="com.songzihao.springboot.entity"
                                targetProject="src\main\java">
                <property name="enableSubPackages" value="false"/>
                <property name="trimStrings" value="false"/>
            </javaModelGenerator>
            <!-- 生成 MyBatis 的 Mapper.xml 文件,targetPackage 指定 mapper.xml 文件的包名, targetProject 指定生成的 mapper.xml 放在 IDEA 的哪个工程下面 -->
            <sqlMapGenerator targetPackage="com.songzihao.springboot.dao"
                             targetProject="src/main/java">
                <property name="enableSubPackages" value="false"/>
            </sqlMapGenerator>
            <!-- 生成 MyBatis 的 Mapper 接口类文件,targetPackage 指定 Mapper 接口类的包名, targetProject 指定生成的 Mapper 接口放在 IDEA 的哪个工程下面 -->
            <javaClientGenerator type="XMLMAPPER"
                                 targetPackage="com.songzihao.springboot.dao"
                                 targetProject="src/main/java">
                <property name="enableSubPackages" value="false"/>
            </javaClientGenerator>
            <!-- 数据库表名及对应的 Java 模型类名 -->
            <table tableName="t_student" domainObjectName="Student"
                   enableCountByExample="false"
                   enableUpdateByExample="false"
                   enableDeleteByExample="false"
                   enableSelectByExample="false"
                   selectByExampleQueryId="false"/>
        </context>
</generatorConfiguration>

在当前项目的maven工程里,选择Plugins插件中的mybatis-generator:generate,即可生成entity包下的实体类、dao包下的接口、mapper文件。



1.3.1 Student实体类

package com.songzihao.springboot.entity;
public class Student {
    private Integer id;
    private String name;
    private Integer age;
    //getter and setter
}

1.3.2 StudentMapperStudentMapper.xml

这两个文件中的代码并不是我们自己写的,而是通过mybatis逆向工程自动生成的!!!(真的强)

package com.songzihao.springboot.dao;
import com.songzihao.springboot.entity.Student;
import org.apache.ibatis.annotations.Mapper;
//扫描dao接口到spring容器
@Mapper
public interface StudentMapper {
    int deleteByPrimaryKey(Integer id);
    int insert(Student record);
    int insertSelective(Student record);
    Student selectByPrimaryKey(Integer id);
    int updateByPrimaryKeySelective(Student record);
    int updateByPrimaryKey(Student record);
}
<?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.songzihao.springboot.dao.StudentMapper">
    <resultMap id="BaseResultMap" type="com.songzihao.springboot.entity.Student">
        <id column="id" jdbcType="INTEGER" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="age" jdbcType="INTEGER" property="age" />
    </resultMap>
    <sql id="Base_Column_List">
        id, name, age
    </sql>
    <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select <include refid="Base_Column_List" />
        from t_student
        where id = #{id,jdbcType=INTEGER}
    </select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
        delete from t_student
        where id = #{id,jdbcType=INTEGER}
    </delete>
    <insert id="insert" parameterType="com.songzihao.springboot.entity.Student">
        insert into t_student (id, name, age)
        values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})
    </insert>
    <insert id="insertSelective" parameterType="com.songzihao.springboot.entity.Student">
        insert into t_student
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="name != null">
                name,
            </if>
            <if test="age != null">
                age,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=INTEGER},
            </if>
            <if test="name != null">
                #{name,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                #{age,jdbcType=INTEGER},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="com.songzihao.springboot.entity.Student">
        update t_student
        <set>
            <if test="name != null">
                name = #{name,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                age = #{age,jdbcType=INTEGER},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>
    <update id="updateByPrimaryKey" parameterType="com.songzihao.springboot.entity.Student">
        update t_student
        set name = #{name,jdbcType=VARCHAR},age = #{age,jdbcType=INTEGER}
        where id = #{id,jdbcType=INTEGER}
    </update>
</mapper>


1.4 service、controller


编写一下业务逻辑层和界面层的代码,这里只对查询方法做一个测试。

package com.songzihao.springboot.service;
import com.songzihao.springboot.entity.Student;
import org.springframework.stereotype.Service;
/**
 *
 */
public interface StudentService {
    Student queryStudentById(Integer id);
}
package com.songzihao.springboot.service.impl;
import com.songzihao.springboot.dao.StudentMapper;
import com.songzihao.springboot.entity.Student;
import com.songzihao.springboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 *
 */
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public Student queryStudentById(Integer id) {
        return studentMapper.selectByPrimaryKey(id);
    }
}
package com.songzihao.springboot.controller;
import com.songzihao.springboot.entity.Student;
import com.songzihao.springboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 *
 */
@Controller
public class StudentController {
    @Autowired
    private StudentService studentService;
    @RequestMapping(value = "/student")
    public @ResponseBody Object student(Integer id) {
        Student student=studentService.queryStudentById(id);
        return student;
    }
}

1.5 SpringBoot核心配置文件、SpringBoot项目启动入口类

#配置内嵌Tomcat端口号
server.port=9090
#配置项目上下文根
server.servlet.context-path=/springboot
#设置连接数据库的配置信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=12345678
package com.songzihao.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


2.使用@MapperScan注解集成MyBatis(将mapper接口和映射文件分开)


其中数据库表、pom文件、逆向工程文件、实体类、servicecontroller 和上面第一个案例是一样的,这里就不再给出代码了。

不一样的地方是下面这些:👇👇👇


2.1 mapper接口、对应的mapper映射文件


注释掉之前的@Mapper注解,因为后面我们会在入口类中使用@MapperScan注解。

package com.songzihao.springboot.mapper;
import com.songzihao.springboot.entity.Student;
import org.apache.ibatis.annotations.Mapper;
//@Mapper
public interface StudentMapper {
    int deleteByPrimaryKey(Integer id);
    int insert(Student record);
    int insertSelective(Student record);
    Student selectByPrimaryKey(Integer id);
    int updateByPrimaryKeySelective(Student record);
    int updateByPrimaryKey(Student record);
}

因为 SpringBoot 不能自动编译接口映射的 xml 文件,还需要手动在 pom 文件中指定,所以有的公司直接将映射文件直接放到 resources 目录下. resources 目录下新建目录 mapper 存放映射文件,将StudentMapper.xml 文件移到 resources/mapper 目录下

这里的mapper映射文件和上面的案例虽然一样,但它存放的位置却改变了。



<?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.songzihao.springboot.mapper.StudentMapper">
  <resultMap id="BaseResultMap" type="com.songzihao.springboot.entity.Student">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="age" jdbcType="INTEGER" property="age" />
  </resultMap>
  <sql id="Base_Column_List">
    id, name, age
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from t_student
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from t_student
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.songzihao.springboot.entity.Student">
    insert into t_student (id, name, age
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.songzihao.springboot.entity.Student">
    insert into t_student
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="name != null">
        name,
      </if>
      <if test="age != null">
        age,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.songzihao.springboot.entity.Student">
    update t_student
    <set>
      <if test="name != null">
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        age = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.songzihao.springboot.entity.Student">
    update t_student
    set name = #{name,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

application.properties 配置文件中指定映射文件的位置,这个配置只有接口和映射文件不在同一个包的情况下,才需要指定。

#配置内嵌Tomcat端口号
server.port=9090
#配置项目上下文根
server.servlet.context-path=/springboot
#设置连接数据库的配置信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=12345678
#指定MyBatis映射文件的路径
mybatis.mapper-locations=classpath:mapper/*.xml

2.2 启动入口类测试


在入口类的上方添加了@MapperScan注解,开启扫描mapper接口的包以及子目录。

package com.songzihao.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//开启扫描mapper接口的包以及子目录
@MapperScan(basePackages = "com.songzihao.springboot.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

 

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
29天前
|
SQL Java 数据库连接
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
123 29
|
1月前
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
64 2
|
1月前
|
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上的开源仓库
296 11
|
2月前
|
缓存 Java 数据库连接
深入探讨:Spring与MyBatis中的连接池与缓存机制
Spring 与 MyBatis 提供了强大的连接池和缓存机制,通过合理配置和使用这些机制,可以显著提升应用的性能和可扩展性。连接池通过复用数据库连接减少了连接创建和销毁的开销,而 MyBatis 的一级缓存和二级缓存则通过缓存查询结果减少了数据库访问次数。在实际应用中,结合具体的业务需求和系统架构,优化连接池和缓存的配置,是提升系统性能的重要手段。
163 4
|
2月前
|
SQL Java 数据库连接
spring和Mybatis的各种查询
Spring 和 MyBatis 的结合使得数据访问层的开发变得更加简洁和高效。通过以上各种查询操作的详细讲解,我们可以看到 MyBatis 在处理简单查询、条件查询、分页查询、联合查询和动态 SQL 查询方面的强大功能。熟练掌握这些操作,可以极大提升开发效率和代码质量。
185 3
|
3月前
|
Java 数据库连接 数据库
spring和Mybatis的逆向工程
通过本文的介绍,我们了解了如何使用Spring和MyBatis进行逆向工程,包括环境配置、MyBatis Generator配置、Spring和MyBatis整合以及业务逻辑的编写。逆向工程极大地提高了开发效率,减少了重复劳动,保证了代码的一致性和可维护性。希望这篇文章能帮助你在项目中高效地使用Spring和MyBatis。
120 1
|
4月前
|
Java 数据库连接 Maven
mybatis使用一:springboot整合mybatis、mybatis generator,使用逆向工程生成java代码。
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和MyBatis Generator,使用逆向工程来自动生成Java代码,包括实体类、Mapper文件和Example文件,以提高开发效率。
217 2
mybatis使用一:springboot整合mybatis、mybatis generator,使用逆向工程生成java代码。
|
4月前
|
SQL JSON Java
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和PageHelper进行分页操作,并且集成Swagger2来生成API文档,同时定义了统一的数据返回格式和请求模块。
146 1
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
|
4月前
|
前端开发 Java Apache
Springboot整合shiro,带你学会shiro,入门级别教程,由浅入深,完整代码案例,各位项目想加这个模块的人也可以看这个,又或者不会mybatis-plus的也可以看这个
本文详细讲解了如何整合Apache Shiro与Spring Boot项目,包括数据库准备、项目配置、实体类、Mapper、Service、Controller的创建和配置,以及Shiro的配置和使用。
968 1
Springboot整合shiro,带你学会shiro,入门级别教程,由浅入深,完整代码案例,各位项目想加这个模块的人也可以看这个,又或者不会mybatis-plus的也可以看这个
|
3月前
|
消息中间件 监控 Java
您是否已集成 Spring Boot 与 ActiveMQ?
您是否已集成 Spring Boot 与 ActiveMQ?
81 0

热门文章

最新文章