SpringBoot整合MyBatis超詳細(xì)教程
1.整合MyBatis操作
前面一篇提到了SpringBoot整合基礎(chǔ)的數(shù)據(jù)源JDBC、Druid操作,實(shí)際項(xiàng)目中更常用的還是MyBatis框架,而SpringBoot整合MyBatis進(jìn)行CRUD也非常方便。
下面從配置模式、注解模式、混合模式三個(gè)方面進(jìn)行說(shuō)明MyBatis與SpringBoot的整合。
1.1.配置模式
MyBatis配置模式是指使用mybatis配置文件的方式與SpringBoot進(jìn)行整合,相對(duì)應(yīng)的就有mybatis-config.xml(用于配置駝峰命名,也可以省略這個(gè)文件)、XxxMapper.xml文件。
主要步驟為:
- 導(dǎo)入mybatis官方starter
- 編寫(xiě)mapper接口。標(biāo)準(zhǔn)@Mapper注解
- 編寫(xiě)sql映射文件并綁定mapper接口
在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息 (建議;配置在mybatis.configuration中,可以省略mybatis-config.xml文件)
下面是具體整合配置步驟:
①引入相關(guān)依賴(lài)pom.xml配置:
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--整合mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
②編寫(xiě)對(duì)應(yīng)Mapper接口:
@Mapper //這個(gè)注解表示了這個(gè)類(lèi)是一個(gè)mybatis的mapper接口類(lèi)
@Repository
public interface UserMapper {
//@Select("select * from user")
List<User> findAllUsers();
//@Insert("insert into user(id, username, password) values (#{id}, #{username}, #{password})")
void insert(User user);
//@Update("update user set username = #{username}, password = #{password} where id = #{id}")
void update(User user);
//@Delete("delete from user where id = #{id}")
void deleteById(Integer id);
}
③在resources下創(chuàng)建對(duì)應(yīng)的mapper文件,對(duì)應(yīng)domain類(lèi),數(shù)據(jù)庫(kù)表單如下:
User類(lèi):
@Data
public class User {
private Integer id;
private String username;
private String password;
}
數(shù)據(jù)庫(kù)user表:

UserMapper.xml文件:
<?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">
<!--namespace表示當(dāng)前mapper的唯一標(biāo)識(shí):一般使用domain的全路徑名+Mapper來(lái)命名-->
<mapper namespace="com.fengye.springboot_mybatis.mapper.UserMapper">
<!--id:方法表示,一般配置對(duì)應(yīng)的方法;
resultType:表示該方法有返回,返回需要封裝到對(duì)應(yīng)實(shí)體的類(lèi)型-->
<select id="findAllUsers" resultType="com.fengye.springboot_mybatis.entity.User">
select * from user
</select>
<insert id="insert" parameterType="com.fengye.springboot_mybatis.entity.User">
insert into user(id, username, password) values (#{id}, #{username}, #{password})
</insert>
<update id="update" parameterType="com.fengye.springboot_mybatis.entity.User">
update user set username = #{username}, password = #{password} where id = #{id}
</update>
<delete id="deleteById" parameterType="Integer">
delete from user where id = #{id}
</delete>
</mapper>
④對(duì)應(yīng)配置application.yml文件:
application.yml
server:
port: 8083
spring:
datasource:
username: root
password: admin
#假如時(shí)區(qū)報(bào)錯(cuò),增加時(shí)區(qū)配置serverTimezone=UTC
url: jdbc:mysql://localhost:3306/mybatis02_0322?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
#config-location: classpath:mybatis/mybatis-config.xml 使用了configuration注解則無(wú)需再指定mybatis-config.xml文件
mapper-locations: classpath:mybatis/mapper/*.xml
configuration: #指定mybatis全局配置文件中的相關(guān)配置項(xiàng)
map-underscore-to-camel-case: true
1.2.注解模式
注解模式使用
主要步驟:
- 導(dǎo)入mybatis官方依賴(lài)
- 注解方式編寫(xiě)mapper接口
- 在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息
可以看到注解模式比配置模式少了編寫(xiě)Mapper.xml文件,簡(jiǎn)化了簡(jiǎn)單SQL語(yǔ)句的xml文件編寫(xiě)。
下面是具體整合步驟:
①創(chuàng)建測(cè)試表單city,對(duì)應(yīng)domain類(lèi):
建表sql:
CREATE TABLE city
(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(30),
state VARCHAR(30),
country VARCHAR(30)
);
City類(lèi):
@Data
public class City {
private Long id;
private String name;
private String state;
private String country;
}
②導(dǎo)入pom.xml與配置模式相同,編寫(xiě)注解式CityMapper接口:
@Mapper
@Repository
public interface CityMapper {
@Select("select * from city where id = #{id}")
public City getCityById(Long id);
/**
* 使用@Options來(lái)增加除Insert語(yǔ)句中其它可選參數(shù),比如插入獲取id主鍵的值
* @param city
*/
@Insert("insert into city(name, state, country) values (#{name}, #{state}, #{country})")
@Options(useGeneratedKeys = true, keyProperty = "id")
public void insert(City city);
@Update("update city set name = #{name}, state = #{state}, country = #{country} where id = #{id}")
public void update(City city);
@Delete("delete from city where id = #{id}")
public void deleteById(Long id);
}
③編寫(xiě)Service層、Controller層:
Service相關(guān):
public interface CityService {
City findCityById(Long id);
void insert(City city);
void update(City city);
void deleteById(Long id);
}
@Service
public class CityServiceImpl implements CityService {
@Autowired
private CityMapper cityMapper;
@Override
public City findCityById(Long id) {
return cityMapper.getCityById(id);
}
@Override
public void insert(City city) {
cityMapper.insert(city);
}
@Override
public void update(City city) {
cityMapper.update(city);
}
@Override
public void deleteById(Long id) {
cityMapper.deleteById(id);
}
}
Controller相關(guān):
@RestController
@RequestMapping("/city/api")
public class CityController {
@Autowired
private CityService cityService;
@RequestMapping("/findCityById/{id}")
public City findCityById(@PathVariable("id") Long id){
return cityService.findCityById(id);
}
@PostMapping("/insert")
public String insert(City city){
cityService.insert(city);
return "insert ok";
}
@PostMapping("/update")
public String update(City city){
cityService.update(city);
return "update ok";
}
@GetMapping("/delete/{id}")
public String delete(@PathVariable("id") Long id){
cityService.deleteById(id);
return "delete ok";
}
}
④對(duì)應(yīng)使用Postman接口進(jìn)行測(cè)試:
簡(jiǎn)單模擬接口POST/GET請(qǐng)求即可:

1.3.混合模式
在實(shí)際項(xiàng)目開(kāi)發(fā)中涉及很多復(fù)雜業(yè)務(wù)及連表查詢(xún)SQL,可以配合使用注解與配置模式,達(dá)到最佳實(shí)踐的目的。
實(shí)際項(xiàng)目操作步驟:
- 引入mybatis-starter
- 配置application.yaml中,指定mapper-location位置即可
- 編寫(xiě)Mapper接口并標(biāo)注@Mapper注解
- 簡(jiǎn)單方法直接注解方式
- 復(fù)雜方法編寫(xiě)mapper.xml進(jìn)行綁定映射
- 主啟動(dòng)類(lèi)上使用@MapperScan("com.fengye.springboot_mybatis.mapper") 簡(jiǎn)化Mapper接口,包下所有接口就可以不用標(biāo)注@Mapper注解
具體配置如下:
@SpringBootApplication
//主啟動(dòng)類(lèi)上標(biāo)注,在XxxMapper中可以省略@Mapper注解
@MapperScan("com.fengye.springboot_mybatis.mapper")
public class SpringbootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisApplication.class, args);
}
}
@Repository
public interface CityMapper {
@Select("select * from city where id = #{id}")
public City getCityById(Long id);
/**
* 使用@Options來(lái)增加除Insert語(yǔ)句中其它可選參數(shù),比如插入獲取id主鍵的值
* @param city
*/
@Insert("insert into city(name, state, country) values (#{name}, #{state}, #{country})")
@Options(useGeneratedKeys = true, keyProperty = "id")
public void insert(City city);
@Update("update city set name = #{name}, state = #{state}, country = #{country} where id = #{id}")
public void update(City city);
@Delete("delete from city where id = #{id}")
public void deleteById(Long id);
}
本博客參考寫(xiě)作文檔:
SpringBoot2核心技術(shù)與響應(yīng)式編程
博客涉及代碼示例均已上傳至github地址:
到此這篇關(guān)于SpringBoot整合MyBatis超詳細(xì)教程的文章就介紹到這了,更多相關(guān)SpringBoot整合MyBatis內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
什么情況下會(huì)出現(xiàn)java.io.IOException?:?Broken?pipe這個(gè)錯(cuò)誤以及解決辦法
這篇文章主要介紹了什么情況下會(huì)出現(xiàn)java.io.IOException?:?Broken?pipe這個(gè)錯(cuò)誤以及解決辦法的相關(guān)資料,這個(gè)錯(cuò)誤表示通信另一端已關(guān)閉連接,常發(fā)生在客戶(hù)端關(guān)閉連接、網(wǎng)絡(luò)超時(shí)或資源不足等情況,文中將解決辦法介紹的非常詳細(xì),需要的朋友可以參考下2024-10-10
SpringMVC接收與響應(yīng)json數(shù)據(jù)的幾種方式
這篇文章主要給大家介紹了關(guān)于SpringMVC接收與響應(yīng)json數(shù)據(jù)的幾種方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用springmvc具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
使用BufferedReader讀取TXT文件中數(shù)值,并輸出最大值
這篇文章主要介紹了使用BufferedReader讀取TXT文件中數(shù)值,并輸出最大值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
SSH框架網(wǎng)上商城項(xiàng)目第11戰(zhàn)之查詢(xún)和刪除商品功能實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了SSH框架網(wǎng)上商城項(xiàng)目第11戰(zhàn)之查詢(xún)和刪除商品功能實(shí)現(xiàn)的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-06-06
springboot 實(shí)現(xiàn)記錄業(yè)務(wù)日志和異常業(yè)務(wù)日志的操作
這篇文章主要介紹了springboot 實(shí)現(xiàn)記錄業(yè)務(wù)日志和異常業(yè)務(wù)日志的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
Java并發(fā)應(yīng)用之任務(wù)執(zhí)行分析
這篇文章主要為大家詳細(xì)介紹了JavaJava并發(fā)應(yīng)用編程中任務(wù)執(zhí)行分析的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-07-07
往DAO類(lèi)中注入@PersistenceContext和@Resource的區(qū)別詳解
這篇文章主要介紹了往DAO類(lèi)中注入@PersistenceContext和@Resource的區(qū)別詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
基于Spring p標(biāo)簽和c標(biāo)簽注入方式
這篇文章主要介紹了Spring p標(biāo)簽和c標(biāo)簽注入方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
Java基礎(chǔ)字符編碼與內(nèi)存流詳細(xì)解讀
這篇文章主要給大家介紹了關(guān)于Java中方法使用的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-08-08

