1. 程式人生 > >Spring Boot MyBatis 連線資料庫

Spring Boot MyBatis 連線資料庫

最近比較忙,沒來得及抽時間把MyBatis的整合發出來,其實mybatis官網在2015年11月底就已經發布了對SpringBoot整合的Release版本,Github上有程式碼:https://github.com/mybatis/mybatis-spring-boot
前面對JPA和JDBC連線資料庫做了說明,本文也是參考官方的程式碼做個總結。

先說個題外話,SpringBoot預設使用 org.apache.tomcat.jdbc.pool.DataSource
現在有個叫 HikariCP 的JDBC連線池元件,據說其效能比常用的 c3p0、tomcat、bone、vibur 這些要高很多。
我打算把工程中的DataSource變更為HirakiDataSource,做法很簡單:
首先在application.properties配置檔案中指定dataSourceType

spring.datasource.type=com.zaxxer.hikari.HikariDataSource

然後在pom中新增Hikari的依賴

<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <!-- 版本號可以不用指定,Spring Boot會選用合適的版本 -->
</dependency>

言歸正傳,下面說在Spring Boot中配置MyBatis。
關於在Spring Boot中整合MyBatis,可以選用基於註解的方式,也可以選擇xml檔案配置的方式。通過對兩者進行實際的使用,還是建議使用XML的方式(官方也建議使用XML)。

下面將介紹通過xml的方式來實現查詢,其次會簡單說一下註解方式,最後會附上分頁外掛(PageHelper)的整合。

一、通過xml配置檔案方式

1、新增pom依賴

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <!-- 請不要使用1.0.0版本,因為還不支援攔截器外掛,1.0.1-SNAPSHOT 是博主寫帖子時候的版本,大家使用最新版本即可 -->
<version>1.0.1-SNAPSHOT</version> </dependency>

2、建立介面Mapper(不是類)和對應的Mapper.xml檔案

定義相關方法,注意方法名稱要和Mapper.xml檔案中的id一致,這樣會自動對應上
StudentMapper.java

package org.springboot.sample.mapper;

import java.util.List;

import org.springboot.sample.entity.Student;

/**
 * StudentMapper,對映SQL語句的介面,無邏輯實現
 *
 * @author 單紅宇(365384722)
 * @myblog http://blog.csdn.net/catoop/
 * @create 2016年1月20日
 */
public interface StudentMapper extends MyMapper<Student> {

    List<Student> likeName(String name);

    Student getById(int id);

    String getNameById(int id);

}

MyMapper.java

package org.springboot.sample.config.mybatis;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

/**
 * 被繼承的Mapper,一般業務Mapper繼承它
 *
 */
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
    //TODO
    //FIXME 特別注意,該介面不能被掃描到,否則會出錯
}

StudentMapper.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="org.springboot.sample.mapper.StudentMapper">

    <!-- type為實體類Student,包名已經配置,可以直接寫類名 -->
    <resultMap id="stuMap" type="Student">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <result property="sumScore" column="score_sum" />
        <result property="avgScore" column="score_avg" />
        <result property="age" column="age" />
    </resultMap>

    <select id="getById" resultMap="stuMap" resultType="Student">
        SELECT *
        FROM STUDENT
        WHERE ID = #{id}
    </select>

    <select id="likeName" resultMap="stuMap" parameterType="string" resultType="list">
        SELECT *
        FROM STUDENT
        WHERE NAME LIKE CONCAT('%',#{name},'%')
    </select>

    <select id="getNameById" resultType="string">
        SELECT NAME
        FROM STUDENT
        WHERE ID = #{id}
    </select>


</mapper> 

3、實體類

package org.springboot.sample.entity;

import java.io.Serializable;

/**
 * 學生實體
 *
 * @author   單紅宇(365384722)
 * @myblog  http://blog.csdn.net/catoop/
 * @create    2016年1月12日
 */
public class Student implements Serializable{

    private static final long serialVersionUID = 2120869894112984147L;

    private int id;
    private String name;
    private String sumScore;
    private String avgScore;
    private int age;

    // get set 方法省略

}

4、修改application.properties 配置檔案

mybatis.mapper-locations=classpath*:org/springboot/sample/mapper/sql/mysql/*Mapper.xml
mybatis.type-aliases-package=org.springboot.sample.entity

5、在Controller或Service呼叫方法測試


    @Autowired
    private StudentMapper stuMapper;

    @RequestMapping("/likeName")
    public List<Student> likeName(@RequestParam String name){
        return stuMapper.likeName(name);
    }

二、使用註解方式

檢視官方git上的程式碼使用註解方式,配置上很簡單,使用上要對註解多做了解。至於xml和註解這兩種哪種方法好,眾口難調還是要看每個人吧。

1、啟動類(我的)中新增@MapperScan註解

@SpringBootApplication
@MapperScan("sample.mybatis.mapper")
public class SampleMybatisApplication implements CommandLineRunner {

    @Autowired
    private CityMapper cityMapper;

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

    @Override
    public void run(String... args) throws Exception {
        System.out.println(this.cityMapper.findByState("CA"));
    }

}

2、在介面上使用註解定義CRUD語句

package sample.mybatis.mapper;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import sample.mybatis.domain.City;

/**
 * @author Eddú Meléndez
 */
public interface CityMapper {

    @Select("SELECT * FROM CITY WHERE state = #{state}")
    City findByState(@Param("state") String state);

}

三、整合分頁外掛

這裡與其說整合分頁外掛,不如說是介紹如何整合一個plugin。MyBatis提供了攔截器介面,我們可以實現自己的攔截器,將其作為一個plugin裝入到SqlSessionFactory中。
Github上有位開發者寫了一個分頁外掛,我覺得使用起來還可以,挺方便的。
Github專案地址: https://github.com/pagehelper/Mybatis-PageHelper

下面簡單介紹下:
首先要說的是,Spring在依賴注入bean的時候,會把所有實現MyBatis中Interceptor介面的所有類都注入到SqlSessionFactory中,作為plugin存在。既然如此,我們整合一個plugin便很簡單了,只需要使用@Bean建立PageHelper物件即可。

1、新增pom依賴

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>4.1.0</version>
</dependency>

2、新增MyBatisConfiguration.java

package org.springboot.sample.config;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.github.pagehelper.PageHelper;

/**
 * MyBatis 配置
 *
 * @author 單紅宇(365384722)
 * @myblog http://blog.csdn.net/catoop/
 * @create 2016年1月21日
 */
@Configuration
public class MyBatisConfiguration {

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

    @Bean
    public PageHelper pageHelper() {
        logger.info("註冊MyBatis分頁外掛PageHelper");
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        pageHelper.setProperties(p);
        return pageHelper;
    }

}

3、分頁查詢測試

    @RequestMapping("/likeName")
    public List<Student> likeName(@RequestParam String name){
        PageHelper.startPage(1, 1);
        return stuMapper.likeName(name);
    }

更多引數使用方法,詳見PageHelper說明文件(上面的Github地址)。