Spring Boot 集成 MyBatis

通过 SpringBoot +MyBatis 实现对数据库学生表的查询操作
实现步骤

(1) 准备数据库

创建新的数据库 springboot,指定数据库字符编码为 utf-8
在这里插入图片描述

(2)创建 05-springboot-mybatis 项目

在这里插入图片描述

(3) 在 pom.xml 中添加相关 jar 依赖

<!--MyBatis 整合 SpringBoot 的起步依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>

<!--MySQL 的驱动依赖-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
<!--<version>5.5.36</version>-->
</dependency>

(4)在 Springboot 的核心配置文件 application.properties 中配置数据源

#设置连接数据库的配置
spring.datasource.driver-class-name=com.mysql.cj.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=1127

(5) 开发代码

➢ 使用 Mybatis 反向工程生成接口、映射文件以及实体 bean,具体步骤参见SpringBoot 工程下使用 Mybatis 反向工程
https://blog.csdn.net/qq_45554909/article/details/113529677
在这里插入图片描述

StudentMappeer.xml

<?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.loey.mapper.StudentMapper">
  
  <resultMap id="BaseResultMap" type="com.loey.model.Student">
    <!--id 标签只能修改主键字段-->
    <!--result 除了主键以外的字段-->
    <!--
        column 数据库中的字段名称
        property 映射对象的属性名称
        jdbcType 列中数据库中字段的类型(可以省略不写)
    -->
    <!--
        resultMap作用:
        1.当数据库中字段名称与实体类对象的属性名不一致时,可以进行转换
        2.当前查询的结果没对应一个表的时候,可以自定义一个结果集
    -->

    <!--
        数据库表字段名称    实体对象属性名称
        user_name           userName
        product_type        productType

    -->
    <!--
        如果数据库中字段名称由多个单词构成,通过MyBatis逆向工程生成的对象属性名称
        会照驼峰命名法规则生成属性名称
        其中:数据库中字段名称由多个单词构成的时候必须使用_下划线分隔
    -->
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="age" jdbcType="INTEGER" property="age" />
  </resultMap>
  
  <!--
       sql语句片段,将公共的部分抽取出来
       通过include标签引用sql语句片段
   -->
  <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.loey.model.Student">
    insert into t_student (id, name, age
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
      )
  </insert>
  <!--
        suffixOverrides 去除多余的逗号
    -->
  <insert id="insertSelective" parameterType="com.loey.model.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.loey.model.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.loey.model.Student">
    update t_student
    set name = #{name,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>
 在 web 包下创建 StudentController 并编写代码 
@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping(value = "/student")
    public @ResponseBody Object student(Integer id) {

        Student student = studentService.queryStudentById(id);

        return student;
    }
}

在 service 包下创建 service 接口并编写代码

public interface StudentService {
    /**
     * 根据学生ID查询详情
     * @param id
     * @return
     */
    Student queryStudentById(Integer id);
}

在 service.impl 包下创建 service 接口并编写代码

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public Student queryStudentById(Integer id) {
        return studentMapper.selectByPrimaryKey(id);
    }
}

如果在 web 中导入 service 存在报错,可以尝试进行如下配置解决
在这里插入图片描述

在 Mybatis 反向工程生成的 StudentMapper 接口上加一个 Mapper 注解
**@Mapper 作用:**mybatis 自动扫描数据持久层的映射文件及 DAO 接口的关系
@Mapper //扫描DAO接口到spring容器,mybatis 自动扫描数据持久层的映射文件及 DAO 接口的关系
public interface StudentMapper {
== 注意:默认情况下,Mybatis 的 xml 映射文件不会编译到 target 的 class 目录下,所以我们需要在 pom.xml 文件中配置 resource==

<build>
<!--手动指定文件夹为resources-->
<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
</resources>

(6) 启动 Application 应用,浏览器访问测试运行

在这里插入图片描述

(7) 在 运 行 的 主 类 上 添 加 注 解 包 扫 描

@MapperScan("com.abc.springboot.mapper")
@SpringBootApplication
//Mybatis 提供的注解:扫描数据持久层的 mapper 映射配置文件,DAO 接口上就不用加@Mapper
// basePackages 通常指定到数据持久层包即可
@MapperScan(basePackages = "com.loey.mapper")
public class Application {

在这里插入图片描述

(8) 将接口和映射文件分开

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

  • 在 resources 目录下新建目录 mapper 存放映射文件,将 StudentMapper.xml 文件移到 resources/mapper 目录下
    在这里插入图片描述
    在 application.properties 配置文件中指定映射文件的位置,这个配置只有接口和映射文件不在同一个包的情况下,才需要指定

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值