最近比較忙,沒來得及抽時間把MyBatis的集成發出來,其實mybatis官網在2015年11月底就已經發布了對SpringBoot集成的Release版本,示例代碼:spring-boot.rar
前面對JPA和JDBC連接數據庫做了說明,本文也是參考官方的代碼做個總結。
先說個題外話,SpringBoot默認使用 org.apache.tomcat.jdbc.pool.DataSource
現在有個叫 HikariCP 的JDBC連接池組件,據說其性能比常用的 c3p0、tomcat、bone、vibur 這些要高很多。
我打算把工程中的DataSource變更為HirakiDataSource,做法很簡單:
首先在application.properties配置文件中指定dataSourceType
1
|
spring.datasource.type=com.zaxxer.hikari.HikariDataSource |
然后在pom中添加Hikari的依賴
1
2
3
4
5
|
< 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依賴
1
2
3
4
5
6
|
< 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package org.springboot.sample.mapper; import java.util.List; import org.springboot.sample.entity.Student; /** * StudentMapper,映射SQL語句的接口,無邏輯實現 * * @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
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<? 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、實體類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package org.springboot.sample.entity; import java.io.Serializable; /** * 學生實體 * * @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 配置文件
1
2
|
mybatis.mapper-locations=classpath*:org/springboot/sample/mapper/sql/mysql/*Mapper.xml mybatis.type-aliases- package =org.springboot.sample.entity |
5、在Controller或Service調用方法測試
1
2
3
4
5
6
7
|
@Autowired private StudentMapper stuMapper; @RequestMapping ( "/likeName" ) public List<Student> likeName( @RequestParam String name){ return stuMapper.likeName(name); } |
二、使用注解方式
查看官方Git上的代碼使用注解方式,配置上很簡單,使用上要對注解多做了解。至于xml和注解這兩種哪種方法好,眾口難調還是要看每個人吧。
1、啟動類(我的)中添加@MapperScan注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@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語句
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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中。
有位開發者寫了一個分頁插件,我覺得使用起來還可以,挺方便的。
項目地址: Mybatis-PageHelper.rar
下面簡單介紹下:
首先要說的是,Spring在依賴注入bean的時候,會把所有實現MyBatis中Interceptor接口的所有類都注入到SqlSessionFactory中,作為plugin存在。既然如此,我們集成一個plugin便很簡單了,只需要使用@Bean創建PageHelper對象即可。
1、添加pom依賴
1
2
3
4
5
|
< dependency > < groupId >com.github.pagehelper</ groupId > < artifactId >pagehelper</ artifactId > < version >4.1.0</ version > </ dependency > |
2、新增MyBatisConfiguration.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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( "注冊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、分頁查詢測試
1
2
3
4
5
|
@RequestMapping ( "/likeName" ) public List<Student> likeName( @RequestParam String name){ PageHelper.startPage( 1 , 1 ); return stuMapper.likeName(name); } |
更多參數使用方法,詳見PageHelper說明文檔。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/catoop/article/details/50553714