MyBatis是一款优秀的持久层框架,原名叫作iBaits,2010年由ApacheSoftwareFoundation迁移到Google Code并改名为MyBatis,2013年又迁移到GitHub上。MyBatis支持定制化SQL、存储过程以及高级映射。MyBatis几乎避免了所有的JDBC代码手动设置参数以及获取结果集。

在传统的SSM框架整合中,使用MyBatis需要大量的XML配置,而在Spring Boot中,MyBatis官方提供了一套自动化配置方案,可以做到MyBatis开箱即用。具体使用步骤如下。

创建项目

springboot 整合MyBatis_java

创建Spring Boot项目,添加MyBatis依赖、数据库驱动依赖以及数据库连接池依赖,代码如下:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <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>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

创建数据库、表、实体类等

 数据库和表

drop table if exists z_book;

create table z_book(
	id int not null auto_increment,
	name varchar(128),
	author varchar(64),
	primary key(id)
) comment '图书';

insert into z_book values (null,'图书名','作者');

实体类

 Book.java

package com.shrimpking.pojo;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/6/5 15:22
 */
public class Book
{
    private int id;
    private String name;
    private String author;

    public Book()
    {
    }

    public Book(String name, String author)
    {
        this.name = name;
        this.author = author;
    }

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getAuthor()
    {
        return author;
    }

    public void setAuthor(String author)
    {
        this.author = author;
    }

    @Override
    public String toString()
    {
        return "Book{" + "id=" + id + ", name='" + name + '\'' + ", author='" + author + '\'' + '}';
    }
}

application.properties

server.port=8099

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimeZone=UTC
spring.datasource.username=root
spring.datasource.password=mysql123

创建数据库访问层

创建BookMapper,代码如下:

BookMapper.java

package com.shrimpking.mapper;

import com.shrimpking.pojo.Book;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/6/5 16:38
 */
@Mapper
public interface BookMapper
{
    /**
     * 增加
     * @param book
     * @return
     */
    int addBook(Book book);

    /**
     * 修改
     * @param book
     * @return
     */
    int updateBookById(Book book);

    /**
     * 删除
     * @param id
     * @return
     */
    int deleteBookById(int id);

    /**
     * 根据id查询
     * @param id
     * @return
     */
    Book getBookById(int id);

    /**
     * 查询全部
     * @return
     */
    List<Book> getAllBooks();

}

代码解释:

• 在项目的根包下面创建一个子包Mapper,在Mapper中创建BookMapper。

• 有两种方式指明该类是一个Mapper:

第一种如前面的代码所示,在BookMapper上添加@Mapper注解,表明该接口是一个MyBatis中的Mapper,这种方式需要在每一个Mapper上都添加注解;

还有一种简单的方式是在配置类上添加@MapperScan("org.shrimpking.mapper")注解,表示扫描org.shirmpking.mapper包下的所有接口作为Mapper,这样就不需要在每个接口上配置@Mapper注解了。

@SpringBootApplication
//@MapperScan("com.shrimpking.mapper")
public class Springboot31MybatisApplication
{

    public static void main(String[] args)
    {
        SpringApplication.run(Springboot31MybatisApplication.class, args);
    }

}

创建BookMapper.xml

在与BookMapper相同的位置创建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.shrimpking.mapper.BookMapper">

    <!-- 增加   -->
    <insert id="addBook" parameterType="com.shrimpking.pojo.Book">
        insert into z_book(name,author) values (#{name},#{author})
    </insert>

    <!-- 修改   -->
    <update id="updateBookById" parameterType="com.shrimpking.pojo.Book">
        update z_book set name = #{name},author = #{author} where id = #{id}
    </update>

    <!-- 删除   -->
    <delete id="deleteBookById" parameterType="int">
        delete from z_book where id = #{id}
    </delete>

    <!-- 根据id查询   -->
    <select id="getBookById" parameterType="int" resultType="com.shrimpking.pojo.Book">
        select id,name,author from z_book where id = #{id}
    </select>

    <!-- 查询全部   -->
    <select id="getAllBooks" resultType="com.shrimpking.pojo.Book">
        select * from z_book
    </select>

</mapper>

代码解释:

• 针对BookMapper接口中的每一个方法都在BookMapper.xml中列出了实现。

• #{}用来代替接口中的参数,实体类中的属性可以直接通过#{实体类属性名}获取。

创建Service和Controller

创建BookService与BookController,代码如下:

BookService.java

package com.shrimpking.service;

import com.shrimpking.mapper.BookMapper;
import com.shrimpking.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/6/5 17:01
 */
@Service
public class BookService
{
    @Autowired
    private BookMapper bookMapper;


    public int addBook(Book book)
    {
        return bookMapper.addBook(book);
    }

    public int updateBookById(Book book)
    {
        return bookMapper.updateBookById(book);
    }

    public int deleteBookById(int id)
    {
        return bookMapper.deleteBookById(id);
    }

    public Book getBookById(int id)
    {
        return bookMapper.getBookById(id);
    }

    public List<Book> getAllBooks()
    {
        return bookMapper.getAllBooks();
    }
}

BookController.java

package com.shrimpking.controller;

import com.shrimpking.pojo.Book;
import com.shrimpking.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/6/5 17:08
 */
@RestController
public class BookController
{
    @Autowired
    private BookService bookService;

    @GetMapping("/bookOp")
    public void bookOperation()
    {
        //增加
        Book book1 = new Book();
        book1.setName("高中英语");
        book1.setAuthor("人教版");
        int result1 = bookService.addBook(book1);
        System.out.println("addBook>>>" + result1);

        //修改
        Book book2 = new Book("大学英语","高教社");
        book2.setId(1);
        int result2 = bookService.updateBookById(book2);
        System.out.println("updateBook>>>" + result2);

        //根据id查询
        Book book = bookService.getBookById(1);
        System.out.println("getBookById>>>" + book.toString());

        //删除
        int result3 = bookService.deleteBookById(1);
        System.out.println("deleteBookById>>>" + result3);

        //查询全部
        List<Book> allBooks = bookService.getAllBooks();
        for (Book bk : allBooks)
        {
            System.out.println("getAllBooks>>>" + bk.toString());
        }
    }
}

配置pom.xml文件

在Maven工程中,XML配置文件建议写在resources目录下,但是上文的Mapper.xml文件写在包下,Maven在运行时会忽略包下的XML文件,因此需要在pom.xml文件中重新指明资源文件位置,配置如下:

<resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>

总pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.12</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.shrimpking</groupId>
    <artifactId>springboot-31-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-31-mybatis</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <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>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

</project>

接下来在浏览器中输入“http://localhost:8099/bookOp”,即可看到数据库中数据的变化,控制台也打印出相应的日志,如图所示。

springboot 整合MyBatis_spring_02

springboot 整合MyBatis_mybatis_03

 

springboot 整合MyBatis_spring_04

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring