几个概念
1. MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
2. 官网地址:MyBatis-Plus
3. Mybatis 及 Mybatis-Spring 依赖请勿加入项目配置,以免引起版本冲突!! Mybatis-Plus 会自动帮你维护。
4. SqlSessionFactoryBean的两点不同:
- Mybatis提供的:org.mybatis.spring.SqlSessionFactoryBean
- MP提供的:com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean
5. MP依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.4</version>
</dependency>
Mapper的CRUD
1. mapper接口继承BaseMapper<T>可以实现基础的CRUD方法。
2. 需要注意的是,以前的MP版本(比如2.3)有个别方法的使用方式在新版本中做了修改。
3. 上述方法修改到了mapper的选装件中com.baomidou.mybatisplus.extension.injector.methods,配合sql注入器使用。
- int alwaysUpdateSomeColumnById(T entity)
- int insertBatchSomeColumn(List<T> entityList)
- int logicDeleteByIdWithFill(T entity)
public class MySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass,
TableInfo tableInfo) {
List<AbstractMethod> methodList =
super.getMethodList(mapperClass, tableInfo);
/**
* 以下 3 个为内置选装件
* 头 2 个支持字段筛选函数
*/
// 例: 不要指定了 update 填充的字段
methodList.add(new InsertBatchSomeColumn(
i -> i.getFieldFill() != FieldFill.UPDATE));
methodList.add(new AlwaysUpdateSomeColumnById());
methodList.add(new LogicDeleteByIdWithFill());
return methodList;
}
}
4. MP启动时注入SQL原理分析
- 方法来源于 BaseMapper, 有方法就必须有 SQL
- Mapper的本质就是org.apache.ibatis.binding.MapperProxy
- MapperProxy中SqlSession→ SqlSessionFactory→ Configuration→ MappedStatements
Model的CRUD
1. ActiveRecord(简称AR,活动记录)
- 属于ORM(对象关系映射)层,由Rails最早提出,遵循标准的ORM模型
- 表映射到记录,记录映射到对象,字段映射到对象属性
- 每一个数据库表对应创建一个类,类的每一个对象实例对应于数据库中表的一行记录;通常表的每个字段在类中都有相应的Field
- ActiveRecord同时负责把自己持久化,在ActiveRecord中封装了对数据库的访问,即CURD
- ActiveRecord是一种领域模型(Domain Model),封装了部分业务逻辑
2. 实体类继承Model<T>抽象类可以实现基础的CRUD方法
- 需要重写pkVal(),返回主键字段
IService的CRUD
service接口继承IService<T>接口可以实现基础的CRUD方法
条件构造器
Mybatis-Plus 通过QueryWrapper(LambdaQueryWrapper) 和UpdateWrapper(LambdaUpdateWrapper) 继承父类AbstractWrapper生成Sql的where条件。
- AbstractWrapper在之前的版本(比如2.3)中叫做EntityWrapper
- 方法中的第一个入参
boolean condition
表示该条件是否加入最后生成的sql中。 - 使用字段名是数据库表的字段名,而不是实体类中的字段名。
代码生成器
1. MyBatis-Plus从 3.0.3
之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
2. 添加模板引擎依赖,MyBatis-Plus支持Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,也可以采用自定义模板引擎。
3. 示例代码
public class TestMp {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/mp03/src/main/java");
gc.setAuthor("myself");
gc.setOpen(false);
gc.setFileOverride(true);
//设置生成的service接口名首字母是否为I
gc.setServiceName("%sService");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mpdemo?" +
"useUnicode=true&useSSL=false&characterEncoding=utf8");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName(scanner("模块名"));
pc.setParent("com.my.mp");
pc.setController("controller");
pc.setService("service");
pc.setEntity("bean");
mpg.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//全局大写命名
strategy.setCapitalMode(true);
//数据库表映射到实体的命名策略
strategy.setNaming(NamingStrategy.underline_to_camel);
//数据库表字段映射到实体的命名策略
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
//lombok注解模式的实体类
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
//strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
//strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
//设置表前缀,实体类命名将去掉
strategy.setTablePrefix( "tbl_");
mpg.setStrategy(strategy);
//设置模板引擎
//mpg.setTemplateEngine(new VelocityTemplateEngine());
mpg.execute();
}
}