Spring Boot整合Mybatis - 笔记

107 阅读2分钟
  1. 创建数据库表并插入两条语句

    create database testdb default character set utf8;
    use testdb;
    create table book(
        id int(11) not null auto_increment,
        name varchar(128) default null,
        author varchar(64) default null,
        primary key (id)
    )engine=innodb default charset=utf8;
    insert into book values(1,'书1','作者1') (2,'书2','作者2');
    
  2. 创建Spring Boot项目,添加Mybatis依赖、数据库驱动依赖、数据库连接池依赖。

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.0</version>
    </dependency>
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.20</version>
    </dependency>
    
  3. application.properties中配置数据库连接信息,记得url中必须配置时区,否则报错!

    #数据库连接
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    spring.datasource.url=jdbc:mysql://localhost:3306/chapter05?serverTimezone=UTC
    spring.datasource.username=xxxx
    spring.datasource.password=xxxx
    
  4. 创建实体类Book

    package cn.cyj.data.entity;
    
    public class Book {
    
        private Integer id;
        private String name;
        private String author;
        
        //省略setters、getters、toString等
    }
    
  5. 创建数据库访问层BookMapper

    package cn.cyj.data.mapper;
    
    import cn.cyj.data.entity.Book;
    import org.apache.ibatis.annotations.Mapper;
    
    import java.util.List;
    
    @Mapper
    public interface BookMapper {
        int addBook(Book book);
        int deleteBookById(Integer id);
        int updateBookById(Book book);
        Book getBookById(Integer id);
        List<Book> getAllBooks();
    }
    
  6. 创建BookMapper.xml实现BookMapper接口中的方法

    BookMapper.xml与BookMapper同级

    <?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="cn.cyj.data.mapper.BookMapper">
        <insert id="addBook" parameterType="cn.cyj.data.entity.Book">
            INSERT INTO BOOK(NAME,AUTHOR) VALUES(#{name},#{author})
        </insert>
    
        <delete id="deleteBookById" parameterType="int">
            DELETE FROM BOOK WHERE id = #{id}
        </delete>
    
        <update id="updateBookById" parameterType="cn.cyj.data.entity.Book">
            UPDATE book SET name = #{name} , author = #{author} where id=#{id}
        </update>
    
        <select id="getBookById" parameterType="int" resultType="cn.cyj.data.entity.Book">
            SELECT * FROM book WHERE id = #{id}
        </select>
    
        <select id="getAllBooks" resultType="cn.cyj.data.entity.Book">
            SELECT * FROM book
        </select>
    </mapper>
    
    • id对应BookMapper接口中的方法名
    • parameterType对应方法的参数类型
    • resultType对应方法的返回值类型
    • #{}用来代替接口中的参数,实体类中的属性可以直接通过#{实体类属性名}获取
  7. 创建BookService

    package cn.cyj.data.service;
    
    import cn.cyj.data.entity.Book;
    import cn.cyj.data.mapper.BookMapper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class BookService {
        
        @Autowired
        BookMapper bookMapper;
        
        public int addBook(Book book){
            return bookMapper.addBook(book);
        }
    
        public int updateBook(Book book){
            return bookMapper.updateBookById(book);
        }
    
        public int deleteBookById(Integer id){
            return bookMapper.deleteBookById(id);
        }
    
        public Book getBookById(Integer id){
            return bookMapper.getBookById(id);
        }
    
        public List<Book> getAllBooks(){
            return bookMapper.getAllBooks();
        }
    }
    
  8. 创建BookController

    package cn.cyj.data.controller;
    
    import cn.cyj.data.entity.Book;
    import cn.cyj.data.service.BookService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    @RestController
    @RequestMapping("/book")
    public class BookController {
    
        @Autowired
        BookService bookService;
    
        @RequestMapping("/test")
        public void bookTest(){
            Book book1 = new Book();
            book1.setName("黄金时代");
            book1.setAuthor("王小波");
            int i = bookService.addBook(book1);
            System.out.println("addBook>>>" + i );
    
            Book book2 = new Book();
            book2.setId(1);
            book2.setName("我的新书2");
            book2.setAuthor("我2");
            int j = bookService.updateBook(book2);
            System.out.println("updateBook>>>" + j);
    
            Book book3 = bookService.getBookById(8);
            System.out.println("book:" + book3.toString());
    
            int k = bookService.deleteBookById(8);
            System.out.println("deleteByBookId>>>" + k);
    
            List<Book> books = bookService.getAllBooks();
            System.out.println(books.toString());
        }
    }
    
  9. 上面的BookMapper.xml文件在包下,Maven扫描不到,因此要在pom.xml里重新指明资源文件位置。

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
    </build>
    

------------------------ 完结!撒花 ✿✿ヽ(°▽°)ノ✿ ------------------------