【SpringBoot】SpringBoot 整合 MyBatis

一、通过配置

1. 第一步: 引入 starter

       <dependency>
           <groupId>org.mybatis.spring.boot</groupId>
           <artifactId>mybatis-spring-boot-starter</artifactId>
           <version>2.1.4</version>
       </dependency>
分析

引入 mybatis-spring-boot-starter 导入了如下:在这里插入图片描述

配置模式在 —— MybatisAutoConfiguration.class 中规定

MybatisAutoConfiguration.class 为我们配置好了SqlSessionFactory、SqlSession 及 Mapper。

  • SqlSessionFactory

MybatisAutoConfiguration.class 自动配置好 SqlSessionFactory
在这里插入图片描述

  • SqlSession
  1. 自动配置了SqlSessionTemplate ,在 SqlSessionTemplate 中组合了 SqlSession
    在这里插入图片描述
    在这里插入图片描述

  2. 导入 AutoConfiguredMapperScannerRegistrar,拿到 Mappper 接口
    在这里插入图片描述

  • Mapper

为我们写的操作 MyBatis 的接口标注 @Mapper 注解,就会被自动扫描进来
在这里插入图片描述

MyBatis 配置项绑定 mybatis 前缀,修改对 MyBatis 的配置,只需要配置文件中 mybatis 下的项即可

@ConfigurationProperties(
    prefix = "mybatis"
)

2. 第二步 —— 创建 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>
</configuration>

我们需要配置的地方,在 configuration 中通过 <setting name="xxx" value="xxx"/>配置

3. 第三步 —— 封装待操作数据库表为实体类

我想操作 Account 数据库表,于是创建 Account 类

package com.wanqing.admin.bean;

import lombok.Data;

/**
 * @description: 账号信息类
 * @author: Liuwanqing
 * @date: 2022-10-23 16:11
 */
@Data
public class Account {
    private long id;
    private int money;
    private String userId;
}

4. 第四步 —— 创建 Mapper 接口

比如我想操作 Account 数据库表,需要创建 AccountMapper 接口放在 mapper 文件下用于操作此 Account 表,在 AccountMapper 接口写自己需要实现的方法

注意:一定要添加 @Mapper 注释,MyBatis 才能自动扫描到

package com.wanqing.admin.mapper;

import com.wanqing.admin.bean.Account;

@Mapper
public interface AccountMapper {
	// 找到并返回当前查询的 id 的 Account
    public Account getAccount(long id);
}

补充: 可通过在 SpringBoot 启动类中,使用 @MapperScan 注释添加 Mapper 查询接口所在位置的方式让 MyBatis 自动扫描,通过这种方式,可不在 Mapper 接口前加入 @Mapper 注释,但是建议还是加上 @Mapper 注释

@SpringBootApplication
@MapperScan("com.wanqing.admin.mapper") // 接口上上不需要标注 Mapper
public class DemoAdminApplication {

    public static void main(String[] args) {

        SpringApplication.run(DemoAdminApplication.class, args);

    }

}

5. 第五步 —— 创建 mapper 包,创建 MyBatis 的 SQL 映射文件

映射文件位置:在这里插入图片描述

<?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.wanqing.admin.mapper.AccountMapper"> <!--    此处修改为你要实现的接口 -->
    <!--    public Account getAccount(long id); -->
    <select id="getAccount" resultType="com.wanqing.admin.bean.Account"> <!--    id 为你要实现的接口的方法名 ,resultType 为该方法返回的类型-->
        select * from Account where id = #{id} <!--  实现此查询的 SQL 语句 -->
    </select>
</mapper>

6. 第六步 —— 在 application.yaml 中添加MyBatis全局配置文件和SQL映射文件位置配置

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml # 全局配置文件位置
  mapper-locations: classpath:mybatis/mapper/*.xml # SQL 映射文件位置

7. 第七步 —— 修改MyBatis配置

MyBatis 全部配置可在如下连接中查到MyBatis全部配置查询

  1. 方法一:在 mybatis-config.xml 全局配置文件中添加配置信息,如下为开启驼峰转换机制:
<?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="mapUnderscoreToCamelCase" value="true"/> 
   </settings>
</configuration>
  1. 在 appliaction.yaml 中在 configration 配置项下配置,代码示例如下:
mybatis:
  configuration: # 修改 MyBatis 配置项
    map-underscore-to-camel-case: true # 开启驼峰命名转换

因此,我们可以直接在 configuration 下进行 MyBatis 配置,因此全局配置文件不是必要的,建议不写全局配置文件。

注意: 不能上述两个方法同时使用,只能使用一个,不相信的可以自己去试试

补充:通过注释的方式写入 SQL 语句

我们也可以在 Mapper 接口中以注释的方式写入 SQL 语句,这种方式适合于查询比较简单的情况。通过这种方式可以不用编写 SQL 映射的 xml 文件

使用方法:

  1. 对查询语句,使用@Select注释,括号内写查询语句
  2. 对插入语句,使用@Insert注释,括号内写插入语句,对插入语句需要开启的选项(通过useGeneratedKeys开启自增主键,keyProperty设置主键为 id),通过@Options注释开启 —— 对复杂的情况,更建议使用 SQL 映射文件

示例:

@Mapper
public interface CityMapper {

    @Select("select * from city where id = #{id}")
    public City getCityById(Long id);

    @Insert("insert into city('name', 'state', 'country') vaules(#{name}, #{state}, #{country})")
    @Options(useGeneratedKeys= true, keyProperty="id")
    public void insert(City city);
}

插入语句映射文件如下:

<?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.wanqing.admin.mapper.CityMapper">
    <!--    public Account getAccount(long id); -->
    <insert id="insert"  useGeneratedKeys="true" keyProperty="id">
        insert into city('name', 'state', 'country') vaules(#{name}, #{state}, #{country})
    </insert>
</mapper>

8. 第八步 —— 编写 Service 类用于测试

package com.wanqing.admin.service;

import com.wanqing.admin.bean.Account;
import com.wanqing.admin.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @description: AccountService 类
 * @author: Liuwanqing
 * @date: 2022-10-23 19:39
 */
@Service
public class AccountService {
    @Autowired
    AccountMapper accountMapper;

    public Account getAcctByid(long id){
        return accountMapper.getAccount(id);
    }
}

测试代码:

package com.wanqing.admin.controller;

import com.wanqing.admin.bean.Account;
import com.wanqing.admin.bean.City;
import com.wanqing.admin.bean.User;
import com.wanqing.admin.service.AccountService;
import com.wanqing.admin.service.CityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

@Slf4j
@Controller
public class indexController {

    @Autowired
    AccountService accountService;

    @ResponseBody
    @GetMapping("/acct")
    public Account getById(@RequestParam("id") Long id){
        return accountService.getAcctByid(id);
    }

}



总结: 在 SpringBoot 中使用 MyBatis 时,上述两种方法可以混合使用。当查询语句较为简单时,使用注释法。当查询语句较为复杂时,使用配置法。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值