MyBatisPlus学习笔记
看完黑马的视频之后写的,应该不是很完整(后面如果发现不全的话再加?)
依赖
下面是mp
、druid
、lombok
、代码生成器
的依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<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>
JDBC参数
在application.yml
里添加
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://124.223.44.144:3306/mybatisplus?serverTimezone=UTC&useSSL=false
username: root
password: dong
标准数据层CRUD功能
在UserDao
中继承BaseMapper<User>
即可使用mp的接口
@Mapper
public interface UserDao extends BaseMapper<User> {
}
对于一般的crud
,mp
给了非常多的接口可以使用,这里不多赘述
lombok
引入lombok
依赖(在文章开头)
然后实体类添加@Data
注解即自动添加get/set
等等方法,注意不包含有参无参构造!!!!
有参无参构造可以用@NoArgsConstructor
、@AllArgsConstructor
如User
实体类:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private String password;
private Integer age;
private String tel;
private Integer deleted;
@Version
private Integer version;
}
mp标准日志输出
在yml里加入以下代码
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
分页功能
添加拦截器
下面的PaginationInnerInterceptor
就是分页拦截器
package top.zhengru.config;
@Configuration
public class MpConfig {
@Bean
public MybatisPlusInterceptor mpInterceptor(){
MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mpInterceptor;
}
}
执行分页查询
@Test
void testGetByPage(){
IPage page = new Page(2,3);
userDao.selectPage(page,null);
System.out.println("当前页码:"+page.getCurrent());
System.out.println("每页显示数:"+page.getSize());
System.out.println("总页数:"+page.getPages());
System.out.println("总条数:"+page.getTotal());
System.out.println("数据:"+page.getRecords());
}
条件查询
常规格式
QueryWrapper qw = new QueryWrapper();
qw.lt("age",23);
List<User> userList = userDao.selectList(qw);
System.out.println(userList);
Lambda格式
QueryWrapper<User> qw = new QueryWrapper<User>();
qw.lambda().lt(User::getAge,23);
List<User> userList = userDao.selectList(qw);
System.out.println(userList);
null值处理
LambdaQueryWrapper<User> lqw =new LambdaQueryWrapper<User>();
lqw.lt(null != uq.getAge(),User::getAge,uq.getAge())
.gt(null != uq.getAge2(),User::getAge,uq.getAge2());
List<User> userList = userDao.selectList(lqw);
System.out.println(userList);
查询投影
LambdaQueryWrapper<User> lqw =new LambdaQueryWrapper<User>();
QueryWrapper<User> lqw =new QueryWrapper<User>();
lqw.select("id","name","age","tel");
lqw.select("count(*) as count,tel");
lqw.groupBy("tel");
List<Map<String, Object>> userList = userDao.selectMaps(lqw);
System.out.println(userList);
模糊查询
like
还有likeLeft
LambdaQueryWrapper<User> lqw =new LambdaQueryWrapper<>();
lqw.like(User::getName,"o");
List<User> users = userDao.selectList(lqw);
System.out.println(users);
还有很多就不列举了…
字段映射与表名映射
@TableName("t_user") //表名映射
@TableField(exist = false) //是否存在
@TableField(value = "pwd") //字段名映射
@TableField(select = false) //是否查询
DML控制
id生成策略控制
如下图
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: assign_id #全局配置
表名前缀
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
table-prefix: t_ #全局配置
逻辑删除
用deleted
标记0
未删除,1
删除
@TableLogic(value = "0",delval = "1")
private Integer deleted;
或者
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
logic-delete-field: deleted #全局配置
logic-not-delete-value: 0
logic-delete-value: 1
乐观锁
用version
标记
用@Version
注解标记实体类属性
@Version
private Integer version;
添加OptimisticLockerInnerInterceptor
拦截器拼接SQL
@Configuration
public class MpConfig {
@Bean
public MybatisPlusInterceptor mpInterceptor(){
MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
mpInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); //拦截器
return mpInterceptor;
}
}
快速开发
同理依赖在文章开头
下面是创建对象的方法和代码生成器的配置文件
AutoGenerator autoGenerator = new AutoGenerator();
autoGenerator.execute();
public class CodeGenerator {
public static void main(String[] args) {
//1.获取代码生成器的对象
AutoGenerator autoGenerator = new AutoGenerator();
//设置数据库相关配置
DataSourceConfig dataSource = new DataSourceConfig();
dataSource.setDriverName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/mybatisplus_db?serverTimezone=UTC");
dataSource.setUsername("root");
dataSource.setPassword("root");
autoGenerator.setDataSource(dataSource);
//设置全局配置
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir(System.getProperty("user.dir")+"/mybatisplus_04_generator/src/main/java"); //设置代码生成位置
globalConfig.setOpen(false); //设置生成完毕后是否打开生成代码所在的目录
globalConfig.setAuthor("黑马程序员"); //设置作者
globalConfig.setFileOverride(true); //设置是否覆盖原始生成的文件
globalConfig.setMapperName("%sDao"); //设置数据层接口名,%s为占位符,指代模块名称
globalConfig.setIdType(IdType.ASSIGN_ID); //设置Id生成策略
autoGenerator.setGlobalConfig(globalConfig);
//设置包名相关配置
PackageConfig packageInfo = new PackageConfig();
packageInfo.setParent("com.aaa"); //设置生成的包名,与代码所在位置不冲突,二者叠加组成完整路径
packageInfo.setEntity("domain"); //设置实体类包名
packageInfo.setMapper("dao"); //设置数据层包名
autoGenerator.setPackageInfo(packageInfo);
//策略设置
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig.setInclude("tbl_user"); //设置当前参与生成的表名,参数为可变参数
strategyConfig.setTablePrefix("tbl_"); //设置数据库表的前缀名称,模块名 = 数据库表名 - 前缀名 例如: User = tbl_user - tbl_
strategyConfig.setRestControllerStyle(true); //设置是否启用Rest风格
strategyConfig.setVersionFieldName("version"); //设置乐观锁字段名
strategyConfig.setLogicDeleteFieldName("deleted"); //设置逻辑删除字段名
strategyConfig.setEntityLombokModel(true); //设置是否启用lombok
autoGenerator.setStrategy(strategyConfig);
//2.执行生成操作
autoGenerator.execute();
}
}
评论
匿名评论隐私政策
✅ 你无需删除空行,直接评论以获取最佳展示效果