【springBoot】Springboot整合mybatis

前言

本博客用springboot通过注解版和配置文件版两种方式整合mybatis

1、pom坐标
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
2、yml文件
server:
  port: 8083
spring:
  datasource:
    username: root
    password: XXXXXXXXX
    url: jdbc:mysql://152.136.203.163:3306/jdbc?useUnicode=true&characterEncoding=UTF-8  #防止插入的数据乱码
mybatis:
  configuration:
    map-underscore-to-camel-case: true # 数据库中的下划线转驼峰配置

3、用springbootTest进行测试是否数据库连接成功
@RunWith(SpringRunner.class)
@SpringBootTest
public class Testd {
    @Autowired
    DataSource dataSource;
    @Test
    public void testDatasource() throws SQLException {
        System.out.println(dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

在这里插入图片描述
如下图默认数据源用的是hikari.HikariDataSource作为数据源头。这样就代表数据库连接成功了

4、准备两个实体Department 、Employee

在这里插入图片描述

5、用注解的方式访问数据库

5.1 mapper

@mapper用来指定这是操作数据库的mapper

// 指定这是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper {
    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int deleteDeptByid(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id")  // 主键自增长(插入数据后要根据数据的id进行其他的操作问题)
    @Insert("insert into department(department_name) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set department_name=#{departmentName} where id = #{id}")
    public int updateDept(Department department);
}

注意以上都是设计到一个参数,如果是两个参数,那么必须要用@param注解
eg

@Select("select * from user where id=#{id}" && pwd=#{pwd})
    User getUserById(@Param("id") int id,@Param("pwd") int pwd);

基本类型的参数或者String类型,需要加上
引用类型不需要加
如果只有一个基本类型的话,可以忽略,但是建议都加上!
我们在SQL中引用的就是我们这里的@Param("")中设定的属性名

5.2 controller(resultFul风格接口)
@RestController
public class DeptController {
    @Autowired
    private DepartmentMapper departmentMapper;

    @PostMapping ("/dept")
    public Department insertDepartment(@RequestBody Department department){
         this.departmentMapper.insertDept(department);
         return department;
    }

    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id){
       return this.departmentMapper.getDeptById(id);
    }
    @PutMapping("/dept")
    public int updateDepartment(@RequestBody Department department){
       return this.departmentMapper.updateDept(department);
    }
    
    @DeleteMapping("/dept/{id}")
    public int deleteDepartment(@PathVariable("id") Integer id){
        return this.departmentMapper.deleteDeptByid(id);
    }
}
5.3 用postman测试接口

就测试一个,插入的,如下图,先改成post请求,输入一个参数,然后返回一个带id的数据,这个带id是主键自增长实现的
在这里插入图片描述

6、用配置文件的方式
6.1mapper

首先我们为了不用每一个接口都写上@Mapper注解,我们可以在启动类上加上@MapperScan来讲接口扫描到容器中。

@MapperScan("com.atguigu.testdata.mapper")  // 将mapper接口扫描到容器中

mapper

//@Mapper或者@MapperScan将接口扫描到容器中
public interface EmployeeMapper {
    public  Employee getEmpById(Integer id);
    public void insertEmp(Employee employee);
}
6.2 配置文件

(1)首先Mybatis 托管到了gitHub上,所以我们进入到gitHub上,然后搜索Mybatis在这里插入图片描述
(2)点击mybatis3 ,进入到新的页面,然后找到文档
在这里插入图片描述

(3)进入到mybatis 的官方文档,我们点击Getting Started 然后找到Exploring Mapped SQL Statements,复制下面内容到我们的.xml文件中
在这里插入图片描述
在这里插入图片描述
(4)EmployeeMapper.xml:
在这里插入图片描述

(5)写我们的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.atguigu.testdata.mapper.EmployeeMapper">  <!--namespace是mapper下的接口-->
    <select id="getEmpById" resultType="com.atguigu.testdata.entity.Employee">
        select * from employee where id=#{id}
    </select>

    <insert id="insertEmp" useGeneratedKeys="true" keyProperty="id">
        insert into employee(lastName,email,gender,d_id) values (#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>

(6) 在配置文件中设置.xml生效

 #如下让mybatis知道xml文件的存在,mapper-locations是一个数组,我们可以配置多个
  mapper-locations: mybatis/mapper/*.xml

(7) Controller

@RestController
public class EmpController {

    @Autowired
    private EmployeeMapper employeeMapper;

    @GetMapping("/emp/{id}")
    public Employee getEmp(@PathVariable("id") Integer id){
        return this.employeeMapper.getEmpById(id);
    }

    @PostMapping("/emp")
    public Employee InsertEmp(@RequestBody Employee employee){
         this.employeeMapper.insertEmp(employee);
         return employee;
    }
}

总结

在写demo的过程中遇到了一个特别难搞的问题,就是怎么都不能将EmployeeMapper.xml让mybatis识别,最后我们可以尝试clean install 就可以成功解决问题

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值