Spring boot

使用Spring Boot与MyBatis集成

2016-12-19  本文已影响785人  蓝色的咖啡

上一节我们使用JPA来进行数据库操作,这次我们集成MyBatis来操作数据库。Spring Boot与MyBatis集成有两种方式,一种是基于注解,一种是基于XML配置文件。我个人更喜欢使用XML方式,因为更直观,也更容易维护。喜欢使用注解的同学可以移步至http://www.mybatis.org/mybatis-3/zh/java-api.html��。

引入MyBatis及数据库相关依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>

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

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

        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
        </dependency>

数据库配置文件

#HikariDataSource database settings
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot?characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456

spring.datasource.maximum-pool-size=80
spring.datasource.max-idle=10
spring.datasource.max-active=150
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
spring.datasource.validation-query=SELECT 1
spring.datasource.test-on-borrow=false
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=18800
spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=0)

mybatis.mapper-locations=classpath*:com/bluecoffee/mapper/**/*Mapper.xml
mybatis.type-aliases-package=com.bluecoffee.domain.**

创建业务实体类

public class Book {

    private Long bookId;

    private String title;

    private String author;

    private Date createTime;

    public Book(){}

    public Book(Long bookId,String title,String author,Date createTime){
        this.bookId = bookId;
        this.title = title;
        this.author = author;
        this.createTime = createTime;
    }

    public Book(String title,String author,Date createTime){
        this.title = title;
        this.author = author;
        this.createTime = createTime;
    }

    //省略getter/setter方法
}

创建数据库操作接口类

@Mapper
public interface BookDao {

    Book getById(Long bookId);

    void insertBook(Book book);

    void deleteAll();

    void updateByPrimaryKey(Book book);

    List<Book> likeTitle(String title);
}

创建SqlMapper.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.bluecoffee.repository.BookDao">

    <resultMap id="bookMap" type="com.bluecoffee.domain.Book">
        <id property="bookId" column="book_id" />
        <result property="title" column="title" />
        <result property="author" column="author" />
        <result property="createTime" column="create_time" />
    </resultMap>

    <delete id="deleteAll">
        delete from BOOK
    </delete>

    <insert id="insertBook" parameterType="com.bluecoffee.domain.Book">
        INSERT
        INTO BOOK(BOOK_ID,TITLE,AUTHOR,CREATE_TIME)
        VALUES
        (#{bookId},#{title},#{author},#{createTime})
    </insert>

    <select id="getById" resultMap="bookMap" resultType="com.bluecoffee.domain.Book">
        SELECT *
        FROM BOOK
        WHERE  book_id = #{bookId,jdbcType=BIGINT}
    </select>

    <select id="likeTitle" resultMap="bookMap" parameterType="string" resultType="java.util.List">
        SELECT *
        FROM BOOK
        WHERE TITLE LIKE CONCAT('%',#{title},'%')
    </select>

    <update id="updateByPrimaryKey" parameterType="com.bluecoffee.domain.Book" >
        update BOOK
        <set >
            <if test="title != null" >
                title = #{title,jdbcType=VARCHAR},
            </if>
            <if test="author != null" >
                author = #{author,jdbcType=VARCHAR},
            </if>
            <if test="createTime != null" >
                create_time = #{createTime,jdbcType=TIMESTAMP},
            </if>
        </set>
        where book_id = #{bookId,jdbcType=BIGINT}
    </update>

</mapper>

完整的项目目录结构如下所示

工程目录

单元测试用例

    @Test
    public void testBook(){
        try{
            //删除所有书籍
            bookDao.deleteAll();

            //创建10本书
            for(int i=1;i<=10;i++){
                bookDao.insertBook(new Book(Long.parseLong(i + ""), "book" + i, "author" + i, new Date()));
            }

            //根据主键查询
            Book book = bookDao.getById(Long.parseLong("9"));
            Assert.assertEquals("book9",book.getTitle());

            //根据主键更新
            book.setBookId(Long.parseLong("9"));
            book.setTitle("book9_update");
            bookDao.updateByPrimaryKey(book);
            Assert.assertEquals("book9_update",book.getTitle());

            //根据书名模糊查询
            List<Book> books = bookDao.likeTitle("book");
            Assert.assertEquals(10,books.size());

        }catch (Exception ex){
            Assert.fail(ex.getMessage());
        }
    }

数据分页

数据分页有很多种方法,Github上有一个不错的插件,我觉得不错,分享一下,项目地址在Mybatis-PageHelper,下面介绍一下使用方法,详细的文档大家可以自己去Github上看看。

引入PageHelper依赖

        <!-- 分页插件 begin-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
            <version>0.9.5</version>
        </dependency>
        <!-- 分页插件 end-->

对PageHelper进行基本的配置,该配置必须在Spring Boot启动后就加载

package com.bluecoffee.configuration;

import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * MyBatis通用分页插件配置
 *
 * Created by bluecoffee on 16/12/19.
 */
@Configuration
public class MyBatisConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(MyBatisConfiguration.class);

    @Bean
    public PageHelper pageHelper() {
        logger.info("MyBatis PageHelper Register");
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("pageSizeZero", "true");
        p.setProperty("reasonable", "false");
        pageHelper.setProperties(p);
        return pageHelper;
    }
}

对分页进行单元测试

    @Test
    public void testPage(){
        try{
            //删除所有书籍
            bookDao.deleteAll();

            //创建8本书
            for(int i=1;i<=8;i++){
                bookDao.insertBook(new Book(Long.parseLong(i + ""), "book" + i, "author" + i, new Date()));
            }

            //根据书名模糊查询,返回第一页数据,每页最多5条数据
            PageHelper.startPage(1, 5);
            List<Book> books = bookDao.likeTitle("book");
            Assert.assertEquals(5,books.size());

            PageHelper.startPage(2, 5);
            books = bookDao.likeTitle("book");
            Assert.assertEquals(3,books.size());

        }catch (Exception ex){
            Assert.fail(ex.getMessage());
        }
    }

完整代码戳这里: Chapter 4-1-2 - Spring Boot集成MyBatis访问数据库

上一篇 下一篇

猜你喜欢

热点阅读