這兩天啟動了一個新項目因為項目組成員一直都使用的是mybatis,雖然個人比較喜歡jpa這種極簡的模式,但是為了項目保持統(tǒng)一性技術(shù)選型還是定了 mybatis。到網(wǎng)上找了一下關(guān)于spring boot和mybatis組合的相關(guān)資料,各種各樣的形式都有,看的人心累,結(jié)合了mybatis的官方demo和文檔終于找到了最簡的兩種模式,花了一天時間總結(jié)后分享出來。
orm框架的本質(zhì)是簡化編程中操作數(shù)據(jù)庫的編碼,發(fā)展到現(xiàn)在基本上就剩兩家了,一個是宣稱可以不用寫一句SQL的hibernate,一個是可以靈活調(diào)試動態(tài)sql的mybatis,兩者各有特點(diǎn),在企業(yè)級系統(tǒng)開發(fā)中可以根據(jù)需求靈活使用。發(fā)現(xiàn)一個有趣的現(xiàn)象:傳統(tǒng)企業(yè)大都喜歡使用hibernate,互聯(lián)網(wǎng)行業(yè)通常使用mybatis。
hibernate特點(diǎn)就是所有的sql都用Java代碼來生成,不用跳出程序去寫(看)sql,有著編程的完整性,發(fā)展到最頂端就是spring data jpa這種模式了,基本上根據(jù)方法名就可以生成對應(yīng)的sql了。
mybatis初期使用比較麻煩,需要各種配置文件、實體類、dao層映射關(guān)聯(lián)、還有一大推其它配置。當(dāng)然mybatis也發(fā)現(xiàn)了這種弊端,初期開發(fā)了generator可以根據(jù)表結(jié)果自動生產(chǎn)實體類、配置文件和dao層代碼,可以減輕一部分開發(fā)量;后期也進(jìn)行了大量的優(yōu)化可以使用注解了,自動管理dao層和配置文件等,發(fā)展到最頂端就是今天要講的這種模式了,mybatis-spring-boot-starter就是springboot+mybatis可以完全注解不用配置文件,也可以簡單配置輕松上手。
現(xiàn)在想想spring boot 就是牛逼呀,任何東西只要關(guān)聯(lián)到spring boot都是化繁為簡。
其實就是myBatis看spring boot這么火熱也開發(fā)出一套解決方案來湊湊熱鬧,但這一湊確實解決了很多問題,使用起來確實順暢了許多。mybatis-spring-boot-starter主要有兩種解決方案,一種是使用注解解決一切問題,一種是簡化后的老傳統(tǒng)。
1 無配置文件注解版
就是一切使用注解搞定。
1.1 項目依賴
- 引入連接mysql的必要依賴mysql-connector-java;
- 引入整合MyBatis的核心依賴mybatis-spring-boot-starter;
- 引入tk.mybatis 依賴,實現(xiàn)對實體類的增刪改查的代碼;
- 引入pagerhelper 依賴,實現(xiàn)分頁功能。
<!--整合Mybatis開始-->
<!--1.引入整合MyBatis的核心依賴mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!--2.引入連接mysql的必要依賴mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.43</version>
</dependency>
<!--3.引入tk.mybatis 依賴,實現(xiàn)對實體類的增刪改查的代碼 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.1.3</version>
</dependency>
<!--4.引入pagerhelper 依賴,實現(xiàn)分頁功能 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.1.2</version>
</dependency>
<!--整合Mybatis結(jié)束-->
1.2 application.properties 添加相關(guān)配置
spring.datasource.url=jdbc:mysql://localhost:3306/tdf_db?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#實體類掃描包
mybatis.type-aliases-package=com.pingkeke.springBoot.entity
#Mapper.xml文件掃描目錄
mybatis.mapper-locations=classpath:mapper/*.xml
#駝峰命名
mybatis.configuration.mapUnderscoreToCamelCase=true
#tkmapper 工具類
mapper.mappers=com.pingkeke.springBoot.util.MyMapper
mapper.not-empty=false
mapper.identity=MYSQL
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
springboot會自動加載spring.datasource.*相關(guān)配置,數(shù)據(jù)源就會自動注入到sqlSessionFactory中,sqlSessionFactory會自動注入到Mapper中,對了你一切都不用管了,直接拿起來使用就行了。
1.3 在啟動類中添加對mapper包掃描@MapperScan
package com.pingkeke.springBoot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 在啟動類中添加對mapper包掃描@MapperScan,Note by:CHENQP
*/
@SpringBootApplication
@MapperScan("com.pingkeke.springBoot.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
或者直接在Mapper類上面添加注解@Mapper,建議使用上面那種,不然每個mapper加個注解也挺麻煩的。
1.4 開發(fā)Mapper
db
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `users`
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵id',
`userName` varchar(32) DEFAULT NULL COMMENT '用戶名',
`passWord` varchar(32) DEFAULT NULL COMMENT '密碼',
`user_sex` varchar(32) DEFAULT NULL,
`nick_name` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
entity
package com.pingkeke.springBoot.entity;
import com.pingkeke.springBoot.enums.UserSexEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
* User.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class User {
private Long id;
private String userName;
private String passWord;
private UserSexEnum userSex;
private String nickName;
}
是最關(guān)鍵的一塊,sql生產(chǎn)都在這里;
package com.pingkeke.springBoot.mapper;
import com.pingkeke.springBoot.entity.UserEntity;
import com.pingkeke.springBoot.enums.UserSexEnum;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* UserMapper.
* sql生產(chǎn)都在這里
*
* 為了更接近生產(chǎn)我特地將user_sex、nick_name兩個屬性在數(shù)據(jù)庫加了下劃線和實體類屬性名不一致,
* 另外user_sex使用了枚舉
*
* @Select 是查詢類的注解,所有的查詢均使用這個
@Result 修飾返回的結(jié)果集,關(guān)聯(lián)實體類屬性和數(shù)據(jù)庫字段一一對應(yīng),
如果實體類屬性和數(shù)據(jù)庫屬性名保持一致,就不需要這個屬性來修飾。
@Insert 插入數(shù)據(jù)庫使用,直接傳入實體類會自動解析屬性到對應(yīng)的值
@Update 負(fù)責(zé)修改,也可以直接傳入對象
@delete 負(fù)責(zé)刪除
*/
public interface UserMapper {
@Select("SELECT * FROM users")
@Results({
@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),
@Result(property = "nickName", column = "nick_name")
})
List<UserEntity> getAll();
@Select("SELECT * FROM users WHERE id = #{id}")
@Results({
@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),
@Result(property = "nickName", column = "nick_name")
})
UserEntity getOne(Long id);
@Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})")
void insert(UserEntity user);
@Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}")
void update(UserEntity user);
@Delete("DELETE FROM users WHERE id =#{id}")
void delete(Long id);
}
注意,使用#符號和$符號的不同:
1.5 使用
上面三步就基本完成了相關(guān)dao層開發(fā),使用的時候當(dāng)作普通的類注入進(jìn)入就可以了。
package com.pingkeke.springBoot.mapper;
import com.pingkeke.springBoot.entity.UserEntity;
import com.pingkeke.springBoot.enums.UserSexEnum;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
/**
* UserMapperTest.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
/**
* 在Idea的spring工程里,經(jīng)常會遇到Could not autowire.
* No beans of 'xxxx' type found的錯誤提示。但程序的編譯和運(yùn)行都是沒有問題的,
* 這個錯誤提示并不會產(chǎn)生影響。但紅色的錯誤提示在有些有強(qiáng)迫癥的程序員眼里,多多少少有些不太舒服。
*
* 解決方案
降低Autowired檢測的級別,將Severity的級別由之前的error改成warning或其它可以忽略的級別。
*/
@Autowired
private UserMapper UserMapper;
@Test
public void testInsert() throws Exception {
UserMapper.insert(new UserEntity("aa", "a123456", UserSexEnum.MAN));
UserMapper.insert(new UserEntity("bb", "b123456", UserSexEnum.WOMAN));
UserMapper.insert(new UserEntity("cc", "b123456", UserSexEnum.WOMAN));
Assert.assertEquals(3, UserMapper.getAll().size());
}
@Test
public void testQuery() throws Exception {
List<UserEntity> users = UserMapper.getAll();
System.out.println(users.toString());
}
@Test
public void testUpdate() throws Exception {
String id= "30";
Long userId = Long.valueOf(id).longValue();
UserEntity user = UserMapper.getOne(userId);
System.out.println(user.toString());
user.setNickName("Bobby");
UserMapper.update(user);
Assert.assertTrue(("Bobby".equals(UserMapper.getOne(userId).getNickName())));
}
}
2 整合Swagger2
2.1 添加Swagger2 依賴
<!--整合Swagger2-->
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
2.2 創(chuàng)建Swagger2 配置類:
在Application.java 同級創(chuàng)建一個Swagger2 的配置類:
package com.pingkeke.springBoot;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Swagger2 的配置類.
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket webApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("DemoAPI接口文檔")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.pingkeke.springBoot.controller"))
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Demo使用Swagger2構(gòu)建RESTful APIs")
.description("用戶服務(wù)")
.contact(new Contact("Bobby", "http://petstore.swagger.io/v2/swagger.json", "pingkeke@163.com"))
.version("1.0")
.build();
}
}
2.3 在需要生成Api 的接口添加注解:
package com.pingkeke.springBoot.controller;
import com.pingkeke.springBoot.entity.UserEntity;
import com.pingkeke.springBoot.mapper.UserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* UserController.
* spring boot如何做呢,只需要類添加 @RestController 即可,默認(rèn)類中的方法都會以json的格式返回
*
http://localhost:8080/swagger-ui.html
*
*/
@Api(tags = "用戶管理相關(guān)接口")
@RestController
@RequestMapping(value="/users") // 通過這里配置使下面的映射都在/users下
public class UserController {
@Autowired
private UserMapper userMapper;
@ApiOperation(value="獲取用戶列表", notes="")
@RequestMapping(value={""}, method= RequestMethod.GET)
public List<UserEntity> getUserList() {
List<UserEntity> users=userMapper.getAll();
return users;
}
@ApiOperation(value="創(chuàng)建用戶", notes="根據(jù)User對象創(chuàng)建用戶")
@ApiImplicitParam(name = "user", value = "用戶詳細(xì)實體user", required = true, dataType = "User")
@RequestMapping(value="", method=RequestMethod.POST)
public void postUser(@RequestBody UserEntity user) {
userMapper.insert(user);
}
@ApiOperation(value="獲取用戶詳細(xì)信息", notes="根據(jù)url的id來獲取用戶詳細(xì)信息")
@ApiImplicitParam(name = "id", value = "用戶ID", required = true, paramType="path", dataType = "Long")
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public UserEntity getUser(@PathVariable Long id) {
UserEntity user=userMapper.getOne(id);
return user;
}
@ApiOperation(value="更新用戶詳細(xì)信息", notes="根據(jù)url的id來指定更新對象,并根據(jù)傳過來的user信息來更新用戶詳細(xì)信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用戶ID", required = true, paramType="path", dataType = "Long"),
@ApiImplicitParam(name = "user", value = "用戶詳細(xì)實體user", required = true, dataType = "User")
})
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public void putUser(@PathVariable Long id, @RequestBody UserEntity user) {
userMapper.update(user);
}
@ApiOperation(value="刪除用戶", notes="根據(jù)url的id來指定刪除對象")
@ApiImplicitParam(name = "id", value = "用戶ID", required = true, paramType="path", dataType = "Long")
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public void deleteUser(@PathVariable Long id) {
userMapper.delete(id);
}
}
完成上述代碼添加上,啟動Spring Boot程序,訪問:http://localhost:8080/swagger-ui.html
。就能看到前文所展示的RESTful API的頁面。我們可以再點(diǎn)開具體的API請求,以POST類型的/users請求為例,可找到上述代碼中我們配置的Notes信息以及參數(shù)user的描述信息,如下圖所示。

3 極簡xml版本
極簡xml版本保持映射文件的老傳統(tǒng),優(yōu)化主要體現(xiàn)在不需要實現(xiàn)dao的是實現(xiàn)層,系統(tǒng)會自動根據(jù)方法名在映射文件中找對應(yīng)的sql.
3.1 配置
pom文件和上個版本一樣,只是application.properties新增以下配置
#實體類掃描包
mybatis.type-aliases-package=com.pingkeke.springBoot.entity
#駝峰命名
mybatis.configuration.mapUnderscoreToCamelCase=true
#Mapper.xml文件掃描目錄
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
指定了mybatis基礎(chǔ)配置文件和實體類映射文件的地址
mybatis-config.xml 配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
</configuration>
這里也可以添加一些mybatis基礎(chǔ)的配置
3.2 添加User的映射文件
<?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="com.pingkeke.springBoot.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.pingkeke.springBoot.entity.UserEntity" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="userName" property="userName" jdbcType="VARCHAR" />
<result column="passWord" property="passWord" jdbcType="VARCHAR" />
<result column="user_sex" property="userSex" javaType="com.pingkeke.springBoot.enums.UserSexEnum"/>
<result column="nick_name" property="nickName" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
id, userName, passWord, user_sex, nick_name
</sql>
<select id="getAll" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM users
</select>
<select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM users
WHERE id = #{id}
</select>
<insert id="insert" parameterType="com.pingkeke.springBoot.entity.UserEntity" >
INSERT INTO
users
(userName,passWord,user_sex)
VALUES
(#{userName}, #{passWord}, #{userSex})
</insert>
<update id="update" parameterType="com.pingkeke.springBoot.entity.UserEntity" >
UPDATE
users
SET
<if test="userName != null">userName = #{userName},</if>
<if test="passWord != null">passWord = #{passWord},</if>
nick_name = #{nickName}
WHERE
id = #{id}
</update>
<delete id="delete" parameterType="java.lang.Long" >
DELETE FROM
users
WHERE
id =#{id}
</delete>
</mapper>
其實就是把上個版本中mapper的sql搬到了這里的xml中了。
3.3 編寫Dao層的代碼
package com.pingkeke.springBoot.mapper;
import com.pingkeke.springBoot.entity.UserEntity;
import java.util.List;
/**
* UserMapper.
* 對比上一步這里全部只剩了接口方法。
*/
public interface UserMapper {
List<UserEntity> getAll();
UserEntity getOne(Long id);
void insert(UserEntity user);
void update(UserEntity user);
void delete(Long id);
}
對比上一步這里全部只剩了接口方法。
3.4 使用
使用和上個版本沒有任何區(qū)別。
3.5 如何選擇
兩種模式各有特點(diǎn),注解版適合簡單快速的模式,其實像現(xiàn)在流行的這種微服務(wù)模式,一個微服務(wù)就會對應(yīng)一個自已的數(shù)據(jù)庫,多表連接查詢的需求會大大的降低,會越來越適合這種模式。
老傳統(tǒng)模式比適合大型項目,可以靈活的動態(tài)生成SQL,方便調(diào)整SQL,也有痛痛快快,洋洋灑灑的寫SQL的感覺。