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都能化繁為簡。

Spring Boot系列:如何優雅的使用 Mybatis

二、mybatis-spring-boot-starter

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

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

<code><dependency>
\t<groupid>org.mybatis.spring.boot/<groupid>
\t<artifactid>mybatis-spring-boot-starter/<artifactid>
\t<version>2.1.1/<version>
/<dependency>/<code>

三、無配置註解版

1、添加maven文件

<code><dependencies>
<dependency>
<groupid>org.springframework.boot/<groupid>
<artifactid>spring-boot-starter-data-jdbc/<artifactid>
/<dependency>

<dependency>
<groupid>org.springframework.boot/<groupid>
<artifactid>spring-boot-starter-web/<artifactid>
/<dependency>

<dependency>
<groupid>org.mybatis.spring.boot/<groupid>
<artifactid>mybatis-spring-boot-starter/<artifactid>
<version>2.1.1/<version>
/<dependency>

<dependency>
<groupid>com.oracle.ojdbc/<groupid>
<artifactid>ojdbc8/<artifactid>
<scope>runtime/<scope>

/<dependency>


<dependency>
<groupid>com.alibaba/<groupid>
<artifactid>druid/<artifactid>
<version>1.1.21/<version>
/<dependency>


<dependency>
<groupid>log4j/<groupid>
<artifactid>log4j/<artifactid>
<version>1.2.17/<version>
/<dependency>
/<dependencies>/<code>

2、application.yml添加相關配置

<code>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/<code>

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

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

<code>@MapperScan(value="com.demo.mapper")
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}/<code>

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

3、controller

<code>@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;
}
}/<code>

4、開發mapper

<code>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);
}/<code>
  • @Select 是查詢類的註解,所有的查詢均使用這個
  • @Result 修飾返回的結果集,關聯實體類屬性和數據庫字段一一對應,如果實體類屬性和數據庫屬性名保持一致,就不需要這個屬性來修飾。
  • @Insert 插入數據庫使用,直接傳入實體類會自動解析屬性到對應的值
  • @Update 負責修改,也可以直接傳入對象
  • @delete 負責刪除

4、運行

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

(1)查詢

Spring Boot系列:如何優雅的使用 Mybatis

(2)插入

  • 插入前數據庫狀態
Spring Boot系列:如何優雅的使用 Mybatis

  • 瀏覽器調用controller執行插入
Spring Boot系列:如何優雅的使用 Mybatis

  • 插入後結果查詢
Spring Boot系列:如何優雅的使用 Mybatis

四、極簡XML版本

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

1、配置

pom 文件和上個版本一樣,只是application.yml新增以下配置

<code>mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml/<code>

mybatis-config.xml 配置

<code>
br> PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

<settings>
<setting>
/<settings>
/<configuration>/<code>

2、employeeMapper.xml

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

<select>
SELECT * FROM employee WHERE id=#{id}
/<select>

<insert>
INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
/<insert>
/<mapper>/<code>

3、開發mapper

<code>package com.demo.mapper;

import com.demo.bean.Employee;
import org.mybatis.spring.annotation.MapperScan;

@MapperScan
public interface EmployeeMapper {
public Employee getEmpById(Integer id);

public void insertEmp(Employee employee);
}
/<code>

對比上一步,這裡只需要定義接口方法。

4、運行結果與註解方式無異。

五、兩種模式如何選擇

Spring Boot系列:如何優雅的使用 Mybatis

兩種模式各有特點,註解版適合簡單快速的模式,其實像現在流行的這種微服務模式,一個微服務就會對應一個自己的數據庫,多表連接查詢的需求會大大的降低,會越來越適合這種模式。

老傳統模式比較適合大型項目,可以靈活的動態生成sql,方便調整sql,有的人就是愛寫sql,再配上點存儲過程,越複雜越好,感覺自己越牛,那你就用這個。


分享到:


相關文章: