Spring Boot MyBatis 連接數據庫
來自: http://blog.csdn.net/catoop/article/details/50553714
最近比較忙,沒來得及抽時間把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> <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 {
List<Student> likeName(String name); Student getById(int id); String getNameById(int id);
}</pre>
StudentMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "; <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> </pre>
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 方法省略
}</pre>
4、修改application.properties 配置文件
mybatis.mapper-locations=classpath*:org/springboot/sample/mapper/sql/mysql/*Mapper.xml mybatis.type-aliases-package=org.springboot.sample.entity5、在Controller或Service調用方法測試
@Autowired private StudentMapper stuMapper;@RequestMapping("/likeName") public List<Student> likeName(@RequestParam String name){ return stuMapper.likeName(name); }</pre> <h3 id="二使用注解方式">二、使用注解方式</h3>
查看官方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")); }
}</pre>
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);
}</pre>
其中City就是一個普通Java類。
關于MyBatis的注解,有篇文章講的很清楚,可以參考: http://blog.csdn.net/luanlouis/article/details/35780175三、集成分頁插件
這里與其說集成分頁插件,不如說是介紹如何集成一個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; }
}</pre>
3、分頁查詢測試
@RequestMapping("/likeName") public List<Student> likeName(@RequestParam String name){ PageHelper.startPage(1, 1); return stuMapper.likeName(name); }更多參數使用方法,詳見PageHelper說明文檔(上面的Github地址)。
</div>