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);
    }
}

 

相关实践学习
每个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`注解完成整合
1009 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
|
6月前
|
Java 数据库连接 微服务
若依微服务的Mybatis-plus集成过程:一份详细的入门教程。
以上就是Spring Boot项目中集成MyBatis Plus的详细步骤。集成成功后,你就可以使用Mybatis-plus提供的强大功能,让你的增删改查操作更为简单。以上步骤简单易懂,非常适合初学者使用。希望对您有所帮助。
782 20
|
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与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
684 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
|
Java Maven Docker
gitlab-ci 集成 k3s 部署spring boot 应用
gitlab-ci 集成 k3s 部署spring boot 应用
下一篇
oss云网关配置