不做 curd Boy ,為偷懶而生
1. Mybatis-plus
MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上隻做增強不做改變,為簡化開發、提高效率而生
MP 有很多強大的功能,但筆者常用的還是下面三種:
- 強大的 CRUD 操作
- 内置代碼生成器
- 内置分頁插件
2. Hello World
筆者跟着 官方文檔 走了一遍,是中文文檔!!!
2.1 建立資料庫
DROP TABLE IF EXISTS user;
CREATE TABLE user (
id BIGINT(20) NOT NULL COMMENT '主鍵ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年齡',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '郵箱',
PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
2.2 導入依賴
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
<!-- 非必要 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
引入之後請不要再次引入
MyBatis-Plus
以及
MyBatis
,以避免因版本差異導緻的問題
MyBatis-Spring
2.3 配置
server:
port: 8080
spring:
application:
name: mybatis-plus-test
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&CharacterEncoding=utf-8
username: xxxx
password: xxxx
2.4 編寫代碼
// entity實體類
// 實作序列化接口,MP傳遞參數
@Data
public class User implements Serializable {
private Long id;
private String name;
private Integer age;
private String email;
}
// mapper接口類,繼承了MP的BaseMapper
// 這裡要注意:記得寫泛型
@Repository
public interface UserMapper extends BaseMapper<User> {
}
// 包掃描
// 也可寫個配置了,在配置類上包掃描
@SpringBootApplication
@MapperScan("com.howl.mapper")
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
2.5 測試
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
List<User> userList = userMapper.selectList(null);
userList.forEach(System.out::println);
}
}
3. 常見的方法
我們繼承 MP 的 BaseMapper 或 IService 接口即可,然後就可使用 MP 内置常見的 CURD 方法。下面方法的 Page 和 Wrapper 後面會說明
3.1 BaseMapper
方法 | 說明 |
---|---|
selectById(Serializable id) | |
selectBatchIds(Collection<? extends Serializable> idList) | 批量操作 |
selectOne(Wrapper queryWrapper) | |
selectCount(Wrapper queryWrapper) | |
selectList(Wrapper queryWrapper) | |
selectPage(P page, Wrapper queryWrapper) | |
updateById(T entity) | |
update(T entity, Wrapper updateWrapper) | |
insert(T entity) | |
deleteById(Serializable id); | |
delete(Wrapper queryWrapper) | |
deleteBatchIds(Collection<? extends Serializable> idList) |
3.2 IService
在 BaseMapper 的基礎上添加幾個方法即可,重複的不展示了
saveOrUpdate(T entity) | 根據 @TableId 判斷 |
saveOrUpdate(T entity, Wrapper updateWrapper) | 根據 Wrapper 來判斷 |
saveOrUpdateBatch(Collection entityList) |
4. 常見的注解
筆者使用這個來代替 ResultMap 的,此外還有一些其他用法
- @TableName:表名注解
- @TableId:主鍵注解
- @TableFiled:字段注解(非主鍵)
- @Version:樂觀鎖注解
- @TableLogic:邏輯删除注解
- @OrderBy:内置 SQL 預設指定排序,優先級低于 wrapper 條件查詢
5. 分頁查詢
分頁本質就是幫你修改 SQL 語句,那麼就是通過攔截器來截取你的 SQL 語句然後修改再發送給資料庫執行
5.1 配置攔截器元件
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
5.2 使用 Page 對象
@Test
public void testSelectPage() {
Page<User> page = new Page<>(2,2); // 當curPage、pageSize
userMapper.selectPage(page, null);
page.getRecords().forEach(System.out::println);
}
5.3 Page對象
public class Page<T> implements IPage<T> {
private static final long serialVersionUID = 8545996863226528798L;
protected List<T> records;
protected long total;
protected long size;
protected long current;
protected List<OrderItem> orders;
protected boolean optimizeCountSql;
protected boolean searchCount;
protected String countId;
protected Long maxLimit;
}
6. 條件構造器
一些複雜的 SQL 語句用 Wapper 會顯得特别簡單,本質就是将特殊 SQL 語句用面向對象的方式解決
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.ge("age", 20)
.eq("age", 20)
.ne("age", 20)
.le("age", 20);
queryWrapper.between("age", 20, 30)
.in("age", 1);
queryWrapper.like("name", "Howl")
.notLike("name", "let")
.likeLeft("name", "Ho")
.likeRight("name", "wl");
queryWrapper.orderByAsc("age")
.orderByDesc("age")
.groupBy("age");
7. 填充操作
7.1 删除建表時設定的預設值
在資料庫中删除 default 值
7.2 實體類字段上添加注解
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
7.3 編寫處理器
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("updateTime", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", new Date(), metaObject);
}
}
8. 代碼生成器
AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個子產品的代碼,極大的提升了開發效率。
8.1 添加依賴
generator、velocity在新版本中被移除了
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
8.2 寫配置
public class CodeGenerator {
public static void main(String[] args) {
// 代碼自動生成器
AutoGenerator autoGenerator = new AutoGenerator();
// 全局配置,generator包下的
GlobalConfig globalConfig = new GlobalConfig()
.setOutputDir(System.getProperty("user.dir") + "/src/main/java")
.setAuthor("Howl")
.setServiceName("%sService")
.setOpen(false)
.setFileOverride(false); // 重寫覆寫
// 資料源配置
DataSourceConfig dataSourceConfig = new DataSourceConfig()
.setUrl("jdbc:mysql://1.116.136.137:3306/user")
.setDriverName("com.mysql.jdbc.Driver")
.setUsername("root")
.setPassword("110110110");
// 包配置
PackageConfig packageConfig = new PackageConfig()
// .setModuleName("mp") 多一個包層次,然後Controller映射位址上也會多一個 /mp
.setParent("com.howl");
// 政策配置
StrategyConfig strategyConfig = new StrategyConfig()
// .setInclude("user","") 不寫全部表都建立進來
.setNaming(NamingStrategy.underline_to_camel)
.setColumnNaming(NamingStrategy.underline_to_camel)
.setEntityLombokModel(true)
.setRestControllerStyle(true)
.setControllerMappingHyphenStyle(true); // 位址映射支援下劃線,非駝峰
// 生成器設定以上配置
autoGenerator.setGlobalConfig(globalConfig)
.setDataSource(dataSourceConfig)
.setPackageInfo(packageConfig)
.setStrategy(strategyConfig);
// 執行生成代碼
autoGenerator.execute();
}
}
9. 補充
筆者以前看見日志就怕,現在報錯就老是找日志了,Mybatis 支援多種日志配置,這裡使用了标準輸出
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl