天天看點

Spring Boot:如何優雅的使用 Mybatis

Spring Boot(四):如何優雅的使用 Mybatis

一、前言

Orm架構的本質是簡化程式設計中操作資料庫的編碼,發展到現在,基本上就剩宣稱不用謝一句sql的hibernate,一個是可以靈活調試動态sql的mybatis,兩者各有特點,在企業級系統來發中可以根據需求靈活使用。發現一個有趣的現象:傳統企業大都喜歡hibernate,網際網路行業通常使用mybatis。

hibernate特點就是所有的sql都用java代碼來生成,不用跳出程式去寫sql,有這程式設計的完整性,發展到最頂端就是spring data jpa這種模式,基本上根據方法名就可以生成對應的sql。

mybatis初期使用比較麻煩,需要各種配置檔案、實體類、Dao層映射關系、還有一大堆其他配置檔案。

當然mybatis也有發現了這種弊端,初期開發了generator可以根據表結構自動生成實體類、配置檔案和dao層代碼,可以減輕一部分開發量;後期也進行了大量的優化可以使用注解,自動管理dao層和配置檔案等,發展到最頂級就是今天講的這種springboot+mybatis可以完全注解不用配置檔案,也可以簡單配置輕松上手。

springboot就是牛逼呀,啥玩意關聯springboot都能化繁為簡。

二、mybatis-spring-boot-starter

mybatis-spring-boot-starter主要由兩種解決方案,一種是使用注解解決一切問題,一種的簡化後的老傳統。

當然任何模式都需要先引入mybatis-spring-boot-starter的pom檔案,現在最新版本是

<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>           

三、無配置注解版

1、添加maven檔案

<groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jdbc</artifactId>           
<groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>           
<groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>2.1.1</version>           
<groupId>com.oracle.ojdbc</groupId>
  <artifactId>ojdbc8</artifactId>
  <scope>runtime</scope>           
<groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.1.21</version>           
<groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.17</version>           

2、application.yml添加相關配置

spring:

datasource:

username: mine
password: mine
url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
driver-class-name: oracle.jdbc.driver.OracleDriver
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500           

Spring Boot 會自動加載spring.datasource.*相關配置,資料源就會自動注入到 sqlSessionFactory 中,sqlSessionFactory 會自動注入到 Mapper 中,對了,你一切都不用管了,直接拿起來使用就行了。

在啟動類中添加對 mapper 包掃描@MapperScan

@MapperScan(value="com.demo.mapper")

@SpringBootApplication

public class DemoApplication {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);           

}

或者直接在 Mapper 類上面添加注解@Mapper,建議使用上面那種,不然每個 mapper 加個注解也挺麻煩的

3、controller

@RestController

public class DeptController {

@Autowired
DepartmentMapper departmentMapper;

@GetMapping("/dept/{id}")
public Department getDepartment(@PathVariable("id") Integer id){
    return departmentMapper.getDeptById(id);
}

@GetMapping("/dept")
public int insertDeptById(@PathVariable("id") Integer id,@PathVariable("departmentName") String departmentName){
    int ret = departmentMapper.insertDept(id,departmentName);
    return ret;
}           

4、開發mapper

package com.demo.mapper;

import com.demo.bean.Department;

import org.apache.ibatis.annotations.*;

public interface DepartmentMapper {

@Select("select * from SSH_DEPARTMENT where id=#{id}")
public Department getDeptById(Integer id);

@Delete("delete from SSH_DEPARTMENT where id=#{id}")
public int deleteDeptById(Integer id);

@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into SSH_DEPARTMENT(department_name) values(#{departmentName})")
public int insertDept(Department department);

@Update("update SSH_DEPARTMENT set departmentName=#{DEPARTMENT_NAME} where id=#{id}")
public int updateDept(Department department);           

@Select 是查詢類的注解,所有的查詢均使用這個

@Result 修飾傳回的結果集,關聯實體類屬性和資料庫字段一一對應,如果實體類屬性和資料庫屬性名保持一緻,就不需要這個屬性來修飾。

@Insert 插入資料庫使用,直接傳入實體類會自動解析屬性到對應的值

@Update 負責修改,也可以直接傳入對象

@delete 負責删除

4、運作

上面三步就基本完成了相關 Mapper 層開發,使用的時候當作普通的類注入進入就可以了

(1)查詢

(2)插入

插入前資料庫狀态

浏覽器調用controller執行插入

插入後結果查詢

四、極簡XML版本

極簡 xml 版本保持映射檔案的老傳統,接口層隻需要定義空方法,系統會自動根據方法名在映射檔案中找對應的 Sql

1、配置

pom 檔案和上個版本一樣,隻是application.yml新增以下配置

mybatis.config-location=classpath:mybatis/mybatis-config.xml

mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

mybatis-config.xml 配置

<?xml version="1.0" encoding="UTF-8" ?>

/p>

PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">           
<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>           

2、employeeMapper.xml

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">