? 朋友們, 大家好, 從今天開始我想開一個系列博客。名字起的比較隨意就叫Mybatis-Plus從入門到入土
, 這系列博客的定位是從基礎使用開始, 然后逐步深入全面的了解Mybatis-Plus
框架, 寫這個博客的主要原因是工作中經常用到Mybatis-Plus
框架, 因而對這個框架相對比較了解一些, 順便在寫作的過程中對自身知識查漏補缺, 歡迎小伙伴和我一同步入Mybatis-Plus
之旅, 我們馬上起飛。
快速開始
我們從Mybatis-Plus
官網的快速開始一步步的學習這個框架。
引入Mybatis-Plus相關依賴
對于SpringBoot項目來說, Mybatis-Plus的依賴相對簡單, 只有一個starter。這里我基于Spring Boot2
及mybatis-plus 3.5.12
, 今后的學習也基于該版本。
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.12</version>
</dependency>
配置
- 在
application.yml
配置文件中添加 H2 數據庫的相關配置:
# DataSource Config
spring:datasource:driver-class-name: org.h2.Driverusername: rootpassword: testsql:init:schema-locations: classpath:db/schema-h2.sqldata-locations: classpath:db/data-h2.sql
這里基于H2數據庫, 如果小伙伴手頭有其他數據庫也可以使用, sql-init
中指定的是數據庫的表結構
和示例數據
。關于mybatis-plus具體支持哪些數據庫可以參考https://baomidou.com/introduce/。
- 在 Spring Boot 啟動類中添加
@MapperScan
注解,掃描 Mapper 文件夾:
@SpringBootApplication
@MapperScan("com.example.mybatispluslearning.mapper")
public class MybatisPlusLearningApplication {public static void main(String[] args) {SpringApplication.run(MybatisPlusLearningApplication.class, args);}}
編碼
創建一個User類
@Data
@TableName("sys_user")
public class User {private Long id;private String name;private Integer age;private String email;
}
創建一個UserMapper接口, 這個類繼承了mybatis-plus提供的BaseMapper接口
public interface UserMapper extends BaseMapper<User> {}
測試
@SpringBootTest
public class SampleTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testSelect() {System.out.println(("----- selectAll method test ------"));List<User> userList = userMapper.selectList(null);Assert.isTrue(5 == userList.size(), "");userList.forEach(System.out::println);}}
好了, 小伙伴們, 第一講就講完了, 敬請收看第二講。