【狂神springboot笔记】SpringBoot整合Mybatis

1、添加依赖包和配置数据源

在官网找到对应的依赖

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

数据源不变

application.yml

spring:
  datasource:
    username: root
    password: 12345
    url: jdbc:MysqL://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    driver-class-name: com.MysqL.cj.jdbc.Driver
#这个是指定对应的扫描包和配置文件,相当于不用写mybatis的配置文件了
mybatis:
  type-aliases-package: com.wcy.pojo
  mapper-locations: classpath:mybatis/mapper/*.xml

2、创建pojo和mapper

Books类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}

BookMapper类

import com.wcy.pojo.Books;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

//这个注解表示这是mybatis的一个mapper类
@Mapper
@Repository
public interface BookMapper {
    List<Books> queryAllBooks();
}

BookMapper.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.wcy.mapper.BookMapper">
    <select id="queryAllBooks" resultType="Books">
        select * from ssmbuild.books
    </select>
</mapper>

3、编写控制器

BookController类

@RestController
public class BookController {

    @Autowired
    private BookMapper bookMapper;

    @GetMapping("/queryAllBooks")
    public List<Books> queryAllBooks() {
        List<Books> bookList = bookMapper.queryAllBooks();
        for (Books book : bookList) {
            System.out.println(book);
        }
        return bookList;
    }
}

测试结果:

相关文章

今天小编给大家分享的是MyBatis批量查询、插入、更新、删除如...
今天小编给大家分享的是Mybatis操作多数据源实现的方法,相信...
本篇文章和大家了解一下mybatis集成到spring的方式有哪些。有...
今天小编给大家分享的是mybatis-plus分页查询的3种方法,相信...
本篇内容主要讲解“mybatis之BaseTypeHandler怎么使用”,感...
这篇文章主要介绍了mybatisforeach怎么传两个参数的相关知识...