mybatis-plus学习记录(详细)
文章目錄
- mybatis-plus
- MyBatis Plus 快速上手
- 常用注解
- 查詢
- 自定義 SQL(多表關聯查詢)
- 添加
- 刪除
- 修改
- MyBatisPlus自動生成
- Spring Boot +MyBatis Plus 打包,發布阿里云
- 獲取代碼地址見下GitHub鏈接
mybatis-plus
官網:https://mp.baomidou.com/guide/
國產的開源框架,基于MyBatis
核心功能就是簡化 MyBatis 的開發,提高效率。
MyBatis Plus 快速上手
Spring Boot(2.3.0) + MyBatis Plus(國產的開源框架,并沒有接入到 Spring 官方孵化器中)
2、pom.xml 引入 MyBatis Plus 的依賴
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.3.1.tmp</version> </dependency>3、創建實體類
package com.monkey.mybatisplus.entity;import lombok.Data;@Data public class User {private Integer id;private String name;private Integer age; }4、創建 Mapper 接口
package com.monkey.mybatisplus;import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.monkey.mybatisplus.entity.User;public interface UserMapper extends BaseMapper<User>{ }5、application.yml
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghaiusername: rootpassword: 123456 mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl //打印sql日志6、啟動類需要添加 @MapperScan(“mapper所在的包”),否則無法加載 Mppaer bean。
@SpringBootApplication @MapperScan("com.monkey.mybatisplus.mapper") public class MybatisplusApplication {public static void main(String[] args) {SpringApplication.run(MybatisplusApplication.class, args);}}7、測試
package com.monkey.mybatisplus;import com.monkey.mybatisplus.mapper.UserMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testvoid test(){userMapper.selectList(null).forEach(System.out::println);}}常用注解
@TableName
映射數據庫的表名(如果實體類名和數據庫表名不一致)
import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data;@Data @TableName(value = "user") public class Account {private Integer id;private String name;private Integer age; }@TableId
設置主鍵映射,value 映射主鍵字段名
import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data;@Data public class User {@TableId(value = "id")private Integer num;private String name;private Integer age; }type 設置主鍵類型,主鍵的生成策略
@Data public class User {@TableId(type = IdType.AUTO)private Long id;@TableField(value = "name")private String title;private Integer age; } AUTO(0), NONE(1), INPUT(2), ASSIGN_ID(3), ASSIGN_UUID(4), /** @deprecated */ @Deprecated ID_WORKER(3), /** @deprecated */ @Deprecated ID_WORKER_STR(3), /** @deprecated */ @Deprecated UUID(4);| AUTO | 數據庫自增 |
| NONE | MP set 主鍵,雪花算法實現(默認) |
| INPUT | 需要開發者手動賦值 |
| ASSIGN_ID | MP 分配 ID,Long、Integer、String |
| ASSIGN_UUID | 分配 UUID,Strinig |
INPUT 如果開發者沒有手動賦值,則數據庫通過自增的方式給主鍵賦值,如果開發者手動賦值,則存入該值。
AUTO 默認就是數據庫自增,開發者無需賦值。
ASSIGN_ID MP 自動賦值,雪花算法。
ASSIGN_UUID 主鍵的數據類型必須是 String,自動生成 UUID 進行賦值。
@TableField
映射非主鍵字段,value 映射字段名
exist 表示是否為數據庫字段 false,如果實體類中的成員變量在數據庫中沒有對應的字段,則可以使用 exist,在VO、DTO用得較多。
@Data public class User {@TableId(type = IdType.AUTO)private Long id;@TableField(value = "name")private String title;private Integer age;@TableField(exist = false)private String gender; }select 表示是否查詢該字段
@Data public class User {@TableId(type = IdType.AUTO)private Long id;@TableField(value = "name",select = false)private String title;private Integer age;@TableField(exist = false)private String gender; }fill 表示是否自動填充,將對象存入數據庫的時候,由 MyBatis Plus 自動給某些字段賦值,create_time、update_time
1、給表添加 create_time、update_time 字段
2、實體類中添加成員變量
package com.monkey.mybatisplus.entity;import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data;import java.util.Date;@Data public class User {@TableId(type = IdType.AUTO)private Long id;@TableField(value = "name",select = false)private String title;private Integer age;@TableField(exist = false)private String gender;@TableField(fill = FieldFill.INSERT)private Date createTime;@TableField(fill = FieldFill.INSERT_UPDATE)private Date updateTime; // private Product product; }3、創建自動填充處理器(自動填充時間-接上INSERT INSERT_UPDATE)
package com.monkey.mybatisplus.handler;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component;import java.util.Date;@Component public class MyMetaObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {this.setFieldValByName("createTime",new Date(),metaObject);this.setFieldValByName("updateTime",new Date(),metaObject);}@Overridepublic void updateFill(MetaObject metaObject) {this.setFieldValByName("updateTime",new Date(),metaObject);} }@Version
標記樂觀鎖,通過 version 字段來保證數據的安全性,當修改數據的時候,會以 version 作為條件,當條件成立的時候才會修改成功。
version = 2
線程 1:update … set version = 2 where version = 1
線程2 :update … set version = 2 where version = 1
1、數據庫表添加 version 字段,默認值為 1
2、實體類添加 version 成員變量,并且添加 @Version
package com.monkey.mybatisplus.entity;import com.baomidou.mybatisplus.annotation.*; import lombok.Data;import java.util.Date;@Data public class User {@TableId(type = IdType.AUTO)private Long id;@TableField(value = "name",select = false)private String title;private Integer age;@TableField(exist = false)private String gender;@TableField(fill = FieldFill.INSERT)private Date createTime;@TableField(fill = FieldFill.INSERT_UPDATE)private Date updateTime;@Version //樂觀鎖private Integer version;// private Product product; }3、注冊配置類(讓樂觀鎖生效)
package com.monkey.mybatisplus.config;import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;@Configuration public class MyBatisPlusConfig {@Beanpublic OptimisticLockerInterceptor optimisticLockerInterceptor(){return new OptimisticLockerInterceptor();} }測試:
package com.monkey.mybatisplus;import com.monkey.mybatisplus.mapper.UserMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testvoid test(){userMapper.selectList(null).forEach(System.out::println);}@Testvoid update(){// update ... version = 3 where version = 2User user = mapper.selectById(7);user.setTitle("一號");// update ... version = 3 where version = 2User user = mapper.selectById(7);user.setTitle("二號");mapper.updateById(user1); //樂觀鎖保證修改只執行一次mapper.updateById(user);}}@EnumValue
1、通用枚舉類注解,將數據庫字段映射成實體類的枚舉類型成員變量
package com.monkey.mybatisplus.enums;import com.baomidou.mybatisplus.annotation.EnumValue;public enum StatusEbum {WORK(1,"上班"),REST(0,"休息");StatusEbum(Integer code, String msg) {this.code = code;this.msg = msg;}@EnumValueprivate Integer code;private String msg; } package com.monkey.mybatisplus.entity;import com.baomidou.mybatisplus.annotation.*; import com.monkey.mybatisplus.enums.StatusEbum; import lombok.Data;import java.util.Date;@Data public class User {@TableId(type = IdType.AUTO)private Long id;@TableField(value = "name",select = false)private String title;private Integer age;@TableField(exist = false)private String gender;@TableField(fill = FieldFill.INSERT)private Date createTime;@TableField(fill = FieldFill.INSERT_UPDATE)private Date updateTime;@Versionprivate Integer version;private StatusEbum status;// private Product product; }application.yml
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl //打印sql日志type-enums-package: com.monkey.mybatisplus.enums //掃描枚舉的包2、實現接口方式
package com.monkey.mybatisplus.enums;import com.baomidou.mybatisplus.core.enums.IEnum;public enum AgeEnum implements IEnum<Integer> {ONE(1,"一歲"),TWO(2,"兩歲"),THREE(3,"三歲");private Integer code;private String msg;AgeEnum(Integer code, String msg) {this.code = code;this.msg = msg;}@Overridepublic Integer getValue() {return this.code;} }@TableLogic
映射邏輯刪除(假刪除)
1、數據表添加 deleted 字段
2、實體類添加注解
package com.monkey.mybatisplus.entity;import com.baomidou.mybatisplus.annotation.*; import com.monkey.mybatisplus.enums.AgeEnum; import com.monkey.mybatisplus.enums.StatusEbum; import lombok.Data;import java.util.Date;@Data public class User {@TableId(type = IdType.AUTO)private Long id;@TableField(value = "name",select = false)private String title; // private AgeEnum age;private Integer age;@TableField(exist = false)private String gender;@TableField(fill = FieldFill.INSERT)private Date createTime;@TableField(fill = FieldFill.INSERT_UPDATE)private Date updateTime;@Versionprivate Integer version;private StatusEbum status;@TableLogicprivate Integer deleted;// private Product product; }3、application.yml 添加配置
global-config:db-config:logic-not-delete-value: 0logic-delete-value: 1查詢
@Testvoid select(){//不加任何條件直接全部查詢 // userMapper.selectList(null);QueryWrapper wrapper = new QueryWrapper(); // wrapper.eq("name","梅西2");// Map<String,Object> map = new HashMap<>(); // map.put("name","梅西2"); // map.put("age",18); // wrapper.allEq(map);// wrapper.lt("age",6);//小于 // wrapper.gt("age",6);//大于 // wrapper.ne("name","梅西2");//不等于 // wrapper.ge("age",5);//大于等于// wrapper.like("name","西");//模糊查詢//like '%西' // wrapper.likeLeft("name","西");//模糊查詢//like '西%' // wrapper.likeRight("name","西");//模糊查詢//inSQL聯合查詢 // wrapper.inSql("id","select id from user where id < 10"); // wrapper.inSql("age","select age from user where age > 3");// wrapper.orderByDesc("age");wrapper.orderByAsc("age");wrapper.having("id > 8");System.out.println(userMapper.selectList(wrapper)); } @Testvoid select2(){ // System.out.println(userMapper.selectById(1)); // userMapper.selectBatchIds(Arrays.asList(1,2,3).forEach(System.out::println););//Map 只能做等值判斷,邏輯判斷需要使用 Wrapper 來處理 // Map<String,Object> map = new HashMap<>(); // map.put("id",1); // userMapper.selectByMap(map);// QueryWrapper wrapper = new QueryWrapper(); // wrapper.gt("id",1); // System.out.println(userMapper.selectCount(wrapper));//下面將查詢的結果集封裝到Map中 // userMapper.selectMaps(wrapper).forEach(System.out::println); // userMapper.selectList(wrapper).forEach(System.out::println);//分頁 // Page<User> page = new Page<>(1,5); // Page<User> result = userMapper.selectPage(page, null); // System.out.println(result.getSize()); // System.out.println(result.getTotal()); // System.out.println(result.getRecords().forEach(System.out::println););//將結果封裝到Map中 // Page<Map<String,Object>> page = new Page<>(1,2); //第一頁,每一頁兩條記錄 // userMapper.selectMapsPage(page,null).getRecords().forEach(System.out::println);//返回ids // userMapper.selectObjs(null).forEach(System.out::println);QueryWrapper wrapper = new QueryWrapper();wrapper.eq("id",1);System.out.println(userMapper.selectOne(wrapper));}自定義 SQL(多表關聯查詢)
package com.monkey.mybatisplus.vo;import lombok.Data;@Data public class ProductVo {private Integer category;private Integer count;private String description;private Integer userId;private String userName; } package com.monkey.mybatisplus.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.monkey.mybatisplus.entity.User; import com.monkey.mybatisplus.vo.ProductVo; import org.apache.ibatis.annotations.Select;import java.util.List;public interface UserMapper extends BaseMapper<User>{@Select("select p.*,u.name userName from product p,user u where p.user_id = u.id and u.id = #{id}")List<ProductVo> productList(Integer id); } @Test void product(){userMapper.productList(1).forEach(System.out::println); }添加
@Test void save(){User u = new User();u.setTitle("孫悟空");u.setAge(18);userMapper.insert(u);System.out.println(u); }刪除
@Test void delete(){ // userMapper.deleteById(1); // userMapper.deleteBatchIds(Arrays.asList(1,2));// QueryWrapper wrapper = new QueryWrapper(); // wrapper.eq("age",14); // userMapper.delete(wrapper);Map<String,Object> map = new HashMap<>();map.put("id",10);userMapper.deleteByMap(map); }修改
@Test void update(){ // User user = userMapper.selectById(1); // user.setTitle("梅西2"); // userMapper.updateById(user);// //update ... version = 3 where version = 2 // User user = mapper.selectById(1); // user.setTitle("一號"); // // //update ... version = 3 where version = 2 // User user1 = mapper.selectById(1); // user1.setTitle("二號"); // // userMapper.updateById(user1); // userMapper.updateById(user);User user = userMapper.selectById(1);user.setTitle("小紅");QueryWrapper wrapper = new QueryWrapper();wrapper.eq("age",18);userMapper.update(user,wrapper);}MyBatisPlus自動生成
根據數據表自動生成實體類、Mapper、Service、ServiceImpl、Controller。
1、pom.xml 導入 MyBatis Plus Generator
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.3.1.tmp</version> </dependency><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity</artifactId><version>1.7</version> </dependency>Velocity(默認)、Freemarker、Beetl
2、啟動類
package com.monkey.mybatisplus;import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.StrategyConfig; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;public class Generator {public static void main(String[] args) {//創建generator對象AutoGenerator autoGenerator = new AutoGenerator();//數據源DataSourceConfig dataSourceConfig = new DataSourceConfig();dataSourceConfig.setDbType(DbType.MYSQL);dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");dataSourceConfig.setUsername("root");dataSourceConfig.setPassword("123456");dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");autoGenerator.setDataSource(dataSourceConfig);//全局配置GlobalConfig globalConfig = new GlobalConfig();globalConfig.setOutputDir(System.getProperty("user.dir")+"/src/main/java");globalConfig.setOpen(false); //創建好之后不打開文件夾globalConfig.setAuthor("hhhmonkey");globalConfig.setServiceName("%sService"); //去掉Impl前面的IautoGenerator.setGlobalConfig(globalConfig); //包信息PackageConfig packageConfig = new PackageConfig();packageConfig.setParent("com.monkey.mybatisplus");packageConfig.setModuleName("your");packageConfig.setController("controller");packageConfig.setService("service");packageConfig.setServiceImpl("service.impl");packageConfig.setMapper("mapper");packageConfig.setEntity("entity");autoGenerator.setPackageInfo(packageConfig);//配置策略StrategyConfig strategyConfig = new StrategyConfig(); // strategyConfig.setInclude("user","product"); //默認生成所有表,這里設置只生成部分表strategyConfig.setInclude("user");strategyConfig.setEntityLombokModel(true); //自動添lombok注解strategyConfig.setNaming(NamingStrategy.underline_to_camel);strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel); //駝峰命名autoGenerator.setStrategy(strategyConfig);autoGenerator.execute();} }運行Generator的main方法,可得到自動生成的代碼結構如下圖所示:
在UserController中寫一個接口測試:
package com.monkey.mybatisplus.your.controller;import com.monkey.mybatisplus.your.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.stereotype.Controller; import org.springframework.web.servlet.ModelAndView;/*** <p>* 前端控制器* </p>** @author hhhmonkey* @since 2020-08-19*/ @Controller @RequestMapping("/your/user") public class UserController {@Autowiredprivate UserService userService;@GetMapping("/index")public ModelAndView index(){ModelAndView modelAndView = new ModelAndView();modelAndView.setViewName("index");modelAndView.addObject("list",userService.list());return modelAndView;}}application.yml:
thymeleaf:prefix: classpath:/templates/suffix: .htmlindex.html:
<!DOCTYPE html> <html lang="en"> <html xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><table><tr th:each="user:${list}"><td th:text="${user.id}"></td><td th:text="${user.name}"></td><td th:text="${user.age}"></td></tr></table></body> </html>運行Spring boot應用:
在瀏覽器查看結果:
Spring Boot +MyBatis Plus 打包,發布阿里云
參見楠哥視頻
本文是在視頻學習過程中邊學習邊敲的,如有錯誤歡迎指正,阿里云部分可去學習B站楠哥教學視頻,這里也順便幫楠哥宣傳一下,講課辛苦了,感謝楠哥。
獲取代碼地址見下GitHub鏈接
(可參照代碼看本篇文章,然后自己動手寫,加油!)
github : https://github.com/monkeyhlj/spring-study
總結
以上是生活随笔為你收集整理的mybatis-plus学习记录(详细)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Github上传代码截图过程
- 下一篇: Shiro学习记录(详细)