1. 程式人生 > 其它 >【狂神springboot筆記】SpringBoot整合Mybatis

【狂神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;
    }
}

測試結果: