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的依賴
com.zaxxer HikariCP
言歸正傳,下面說在Spring Boot中配置MyBatis。
關於在Spring Boot中整合MyBatis,可以選用基於註解的方式,也可以選擇xml檔案配置的方式。通過對兩者進行實際的使用,還是建議使用XML的方式(官方也建議使用XML)。
下面將介紹通過xml的方式來實現查詢,其次會簡單說一下註解方式,最後會附上分頁外掛程式(PageHelper)的整合。
一、通過xml設定檔方式1、添加pom依賴
org.mybatis.spring.boot mybatis-spring-boot-starter 1.0.1-SNAPSHOT
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 { List likeName(String name); Student getById(int id); String getNameById(int id);}
StudentMapper.xml
<code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%2D%2D%3E--><mapper namespace="org.springboot.sample.mapper.StudentMapper"> <!--{cke_protected}{C}%3C!%2D%2D%20type%E4%B8%BA%E5%AE%9E%E4%BD%93%E7%B1%BBStudent%EF%BC%8C%E5%8C%85%E5%90%8D%E5%B7%B2%E7%BB%8F%E9%85%8D%E7%BD%AE%EF%BC%8C%E5%8F%AF%E4%BB%A5%E7%9B%B4%E6%8E%A5%E5%86%99%E7%B1%BB%E5%90%8D%20%2D%2D%3E--> <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"> </result></result></result></result></id></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> </code>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.xmlmybatis.type-aliases-package=org.springboot.sample.entity
5、在Controller或Service調用方法測試
@Autowired private StudentMapper stuMapper; @RequestMapping("/likeName") public List 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);}
其中City就是一個普通Java類。
三、整合分頁外掛程式
這裡與其說整合分頁外掛程式,不如說是介紹如何整合一個plugin。MyBatis提供了攔截器介面,我們可以實現自己的攔截器,將其作為一個plugin裝入到SqlSessionFactory中。
Github上有位開發人員寫了一個分頁外掛程式,我覺得使用起來還可以,挺方便的。
Github項目地址: https://github.com/pagehelper/Mybatis-PageHelper
下面簡單介紹下:
首先要說的是,Spring在依賴注入bean的時候,會把所有實現MyBatis中Interceptor介面的所有類都注入到SqlSessionFactory中,作為plugin存在。既然如此,我們整合一個plugin便很簡單了,只需要使用@Bean建立PageHelper對象即可。
1、添加pom依賴
com.github.pagehelper pagehelper 4.1.0
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日 */@Configurationpublic 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 likeName(@RequestParam String name){ PageHelper.startPage(1, 1); return stuMapper.likeName(name); }
更多參數使用方法,詳見PageHelper說明文檔(上面的Github地址)。