Spring Boot MyBatis 連接數(shù)據(jù)庫(kù)配置示例
最近比較忙,沒(méi)來(lái)得及抽時(shí)間把MyBatis的集成發(fā)出來(lái),其實(shí)mybatis官網(wǎng)在2015年11月底就已經(jīng)發(fā)布了對(duì)SpringBoot集成的Release版本,示例代碼:spring-boot_jb51.rar
前面對(duì)JPA和JDBC連接數(shù)據(jù)庫(kù)做了說(shuō)明,本文也是參考官方的代碼做個(gè)總結(jié)。
先說(shuō)個(gè)題外話(huà),SpringBoot默認(rèn)使用 org.apache.tomcat.jdbc.pool.DataSource
現(xiàn)在有個(gè)叫 HikariCP 的JDBC連接池組件,據(jù)說(shuō)其性能比常用的 c3p0、tomcat、bone、vibur 這些要高很多。
我打算把工程中的DataSource變更為HirakiDataSource,做法很簡(jiǎn)單:
首先在application.properties配置文件中指定dataSourceType
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
然后在pom中添加Hikari的依賴(lài)
<dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <!-- 版本號(hào)可以不用指定,Spring Boot會(huì)選用合適的版本 --> </dependency>
言歸正傳,下面說(shuō)在spring Boot中配置MyBatis。
關(guān)于在Spring Boot中集成MyBatis,可以選用基于注解的方式,也可以選擇xml文件配置的方式。通過(guò)對(duì)兩者進(jìn)行實(shí)際的使用,還是建議使用XML的方式(官方也建議使用XML)。
下面將介紹通過(guò)xml的方式來(lái)實(shí)現(xiàn)查詢(xún),其次會(huì)簡(jiǎn)單說(shuō)一下注解方式,最后會(huì)附上分頁(yè)插件(PageHelper)的集成。
一、通過(guò)xml配置文件方式
1、添加pom依賴(lài)
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <!-- 請(qǐng)不要使用1.0.0版本,因?yàn)檫€不支持?jǐn)r截器插件,1.0.1-SNAPSHOT 是博主寫(xiě)帖子時(shí)候的版本,大家使用最新版本即可 --> <version>1.0.1-SNAPSHOT</version> </dependency>
2、創(chuàng)建接口Mapper(不是類(lèi))和對(duì)應(yīng)的Mapper.xml文件
定義相關(guān)方法,注意方法名稱(chēng)要和Mapper.xml文件中的id一致,這樣會(huì)自動(dòng)對(duì)應(yīng)上
StudentMapper.Java
package org.springboot.sample.mapper; import java.util.List; import org.springboot.sample.entity.Student; /** * StudentMapper,映射SQL語(yǔ)句的接口,無(wú)邏輯實(shí)現(xiàn) * * @author 單紅宇(365384722) * @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,一般業(yè)務(wù)Mapper繼承它 * */ public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> { //TODO //FIXME 特別注意,該接口不能被掃描到,否則會(huì)出錯(cuò) }
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為實(shí)體類(lèi)Student,包名已經(jīng)配置,可以直接寫(xiě)類(lèi)名 --> <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、實(shí)體類(lèi)
package org.springboot.sample.entity; import java.io.Serializable; /** * 學(xué)生實(shí)體 * * @author 單紅宇(365384722) * @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調(diào)用方法測(cè)試
@Autowired private StudentMapper stuMapper; @RequestMapping("/likeName") public List<Student> likeName(@RequestParam String name){ return stuMapper.likeName(name); }
二、使用注解方式
查看官方Git上的代碼使用注解方式,配置上很簡(jiǎn)單,使用上要對(duì)注解多做了解。至于xml和注解這兩種哪種方法好,眾口難調(diào)還是要看每個(gè)人吧。
1、啟動(dòng)類(lèi)(我的)中添加@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語(yǔ)句
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就是一個(gè)普通Java類(lèi)。
三、集成分頁(yè)插件
這里與其說(shuō)集成分頁(yè)插件,不如說(shuō)是介紹如何集成一個(gè)plugin。MyBatis提供了攔截器接口,我們可以實(shí)現(xiàn)自己的攔截器,將其作為一個(gè)plugin裝入到SqlSessionFactory中。
有位開(kāi)發(fā)者寫(xiě)了一個(gè)分頁(yè)插件,我覺(jué)得使用起來(lái)還可以,挺方便的。
項(xiàng)目地址: Mybatis-PageHelper_jb51.rar
下面簡(jiǎn)單介紹下:
首先要說(shuō)的是,Spring在依賴(lài)注入bean的時(shí)候,會(huì)把所有實(shí)現(xiàn)MyBatis中Interceptor接口的所有類(lèi)都注入到SqlSessionFactory中,作為plugin存在。既然如此,我們集成一個(gè)plugin便很簡(jiǎn)單了,只需要使用@Bean創(chuàng)建PageHelper對(duì)象即可。
1、添加pom依賴(lài)
<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) * @create 2016年1月21日 */ @Configuration public class MyBatisConfiguration { private static final Logger logger = LoggerFactory.getLogger(MyBatisConfiguration.class); @Bean public PageHelper pageHelper() { logger.info("注冊(cè)MyBatis分頁(yè)插件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、分頁(yè)查詢(xún)測(cè)試
@RequestMapping("/likeName") public List<Student> likeName(@RequestParam String name){ PageHelper.startPage(1, 1); return stuMapper.likeName(name); }
更多參數(shù)使用方法,詳見(jiàn)PageHelper說(shuō)明文檔。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的區(qū)
這篇文章主要介紹了com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的區(qū)別以及設(shè)定serverTimezone的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-09-09Java中List與數(shù)組之間的相互轉(zhuǎn)換
在日常Java學(xué)習(xí)或項(xiàng)目開(kāi)發(fā)中,經(jīng)常會(huì)遇到需要int[]數(shù)組和List列表相互轉(zhuǎn)換的場(chǎng)景,然而往往一時(shí)難以想到有哪些方法,最后可能會(huì)使用暴力逐個(gè)轉(zhuǎn)換法,往往不是我們所滿(mǎn)意的,下面這篇文章主要給大家介紹了關(guān)于Java中List與數(shù)組之間的相互轉(zhuǎn)換,需要的朋友可以參考下2023-05-05SpringBoot自動(dòng)配置之自定義starter的實(shí)現(xiàn)代碼
這篇文章主要介紹了SpringBoot自動(dòng)配置之自定義starter的實(shí)現(xiàn)代碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10Mybatis一對(duì)一延遲加載實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了Mybatis一對(duì)一延遲加載實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10用Java產(chǎn)生100個(gè)1-150間不重復(fù)數(shù)字
這篇文章主要介紹了用Java產(chǎn)生100個(gè)1-150間不重復(fù)數(shù)字,需要的朋友可以參考下2017-02-02