文章目录
依赖
使用 mybatis-plus 需要去掉 mybatis 的依赖
<!--替换mybatis-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
用法
dao层继承com.baomidou.mybatisplus.core.mapper.BaseMapper
下的BaseMapper<T>
方法
List<T> selectList(@Param("ew") Wrapper<T> var1);
查询所有,wapper是条件构造器
int insert(T var1);
插入一个数据
如果主键自增则自动添加,如果没有自增按雪花算法添加
int updateById(@Param("et") T var1);
根据主键更新字段
参数类型是有主键和需要修改字段的实体类对象
T selectById(Serializable var1);
根据主键查数据
List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> var1);
根据主键查数据,批量查数据,通过collection对象传入多个主键
tip:Arrays.asList()
方法可以快速生成collection对象
List<T> selectByMap(@Param("cm") Map<String, Object> var1);
通过 Map 类型的参数传入,需要查询的记录的某些字段名和值(支持多条件查询)
int deleteById(Serializable var1);
根据主键删除
int deleteBatchIds(@Param("coll") Collection<? extends Serializable> var1);
通过主键批量删除,将主键放在collection集合中
int deleteByMap(@Param("cm") Map<String, Object> var1);
通过 Map 类型的参数删除(支持批量删除)
常见问题
no column ‘···’
八成是因为 mybatis-plus 默认开启大写转驼峰,关掉就好
mybatis-plus:
configuration:
map-underscore-to-camel-case: false
There is no getter for property named null in class ···
数据库的主键没指定,默认主键名叫id,如果这个数据库你没设置过主键,或者设置了主键,但主键不叫 id,那么加个注解在pojo层上对应主键的变量上:@TableId
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
@TableId
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
The SQL execution time is too large, please optimize !
原因:超过了设置的sql执行最大时间
在性能分析插件里把时间(括号里的参数)调大
performanceInterceptor.setMaxTime(1);
No gettet for column ‘et’…
自己的方法和BaseMapper里面有方法重名了,‘et’ 字段是默认的主键名。
分页
在配置类里写一个方法即导入了分页插件,注意!配置类需要扫描mapper
// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
做个简单的单元测试,使用一下分页插件
/**
* 测试分页查询
*/
@Test
public void testPage(){
/**
* 参数1:当前页
* 参数2:页面大小
*/
Page<Books> page = new Page<>(1,5);
bookMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
}
通过日志可以看出,本质是通过limit处理的
page对象的方法 | 说明 |
---|---|
getRecords() | 分页后的整页数据 |
getPages() | 一共的页数 |
getCurrent() | 当前第几页 |
getTotal() | 一共多少条数据 |
性能分析插件
设置在 dev 和 test 环境下开启 ,保证效率
// 性能分析插件(只能在dev和test环境下生效)
@Bean
@Profile({"dev","test"})
public PerformanceInterceptor performanceInterceptor(){
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(1);//设置sql的最大执行时间,单位:毫秒
performanceInterceptor.setFormat(true);//是否开启格式化支持(就是输出的sql有格式更清楚)
return performanceInterceptor;
}
格式化示例:
超出最大时间报错:
条件构造器
用来代替 一些复杂的sql
简单示范一下
@Test
public void test01(){
QueryWrapper<Books> wrapper = new QueryWrapper<>();
// bookName字段不为空,bookCounts字段>=7
wrapper.isNotNull("bookName")
.ge("bookCounts",7);
List<Books> books = bookMapper.selectList(wrapper);
books.forEach(System.out::println);
}
可以看到,自动补全的sql为:
这是基本所有的用法,引用一下别人文章里的一张图片
代码自动生成器
简单做个示例 ,更多的自行百度
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
public class AutoCodeTest {
public static void main(String[] args) {
// 代码自动生成器对象
AutoGenerator mpg = new AutoGenerator();
//全局配置
GlobalConfig gc = new GlobalConfig();//包是com.baomidou.mybatisplus.generator.config.GlobalConfig;
String projectPath = System.getProperty("user.dir");//获取项目路径
gc.setOutputDir(projectPath+"/src/main/java");//设置输出目录
gc.setFileOverride(false);//是否覆盖原有的
gc.setServiceName("%sService");//去掉service层接口的 I 前缀
gc.setIdType(IdType.ID_WORKER);//设置主键的算法为初始算法(uuid、雪花算法、自增)
gc.setDateType(DateType.ONLY_DATE);//设置日期类型仅仅只是时间
gc.setSwagger2(true);//自动配置swagger文档
//数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/ssmbuild?serverTimezone=GMT%2B8&characterEncoding=UTF8");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL);
//包的配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.zxt");
pc.setModuleName("blog");
pc.setEntity("pojo");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("comtroller");
//策略配置
StrategyConfig sc = new StrategyConfig();
sc.setInclude("books");//需要的映射的表名(可以多个)
sc.setEntityLombokModel(true);//是否支持lombok生成
sc.setNaming(NamingStrategy.underline_to_camel);//表名命名规则,下划线转驼峰
sc.setColumnNaming(NamingStrategy.underline_to_camel);//列名命名规则,下划线转驼峰
sc.setLogicDeleteFieldName("deleted");//设置逻辑删除的字段名
sc.setVersionFieldName("version");//设置乐观锁的字段
//自动填充配置
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);//插入行数据时,自动填充gmt_create
TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);//插入和修改行数据时,自动填充gmt_modified
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
sc.setTableFillList(tableFills);//注意:自动填充配置也是一种策略
mpg.setGlobalConfig(gc);
mpg.setDataSource(dsc);
mpg.setPackageInfo(pc);
mpg.setStrategy(sc);
mpg.execute();//执行代码构造器
}
}