MybatisPlus的简单使用
Mubatis是什么? MyBatis 本来就是简化 JDBC 操作的!
官网:https://mp.baomidou.com/ MyBatis Plus,简化 MyBatis !
使用mybatisplus的例子:
步骤:1:、创建数据库 mybatis_plus
2、创建user表
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, 'test1@baomidou.com'), (2, 'Jack', 20, 'test2@baomidou.com'), (3, 'Tom', 28, 'test3@baomidou.com'), (4, 'Sandy', 21, 'test4@baomidou.com'), (5, 'Billie', 24, 'test5@baomidou.com'); -- 真实开发中,version(乐观锁)、deleted(逻辑删除)、gmt_create、gmt_modified
3、编写项目,初始化项目!使用SpringBoot初始化!
4、导入依赖:
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis-plus -->
<!-- mybatis-plus 是自己开发,并非官方的! -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
说明:我们使用 mybatis-plus 可以节省我们大量的代码,尽量不要同时导入 mybatis 和 mybatisplus!版本的差异!
5、连接数据库!这一步和 mybatis 相同!
# mysql 5 驱动不同 com.mysql.jdbc.Driver
# mysql 8 驱动不同com.mysql.cj.jdbc.Driver、需要增加时区的配置
spring.datasource.username=root
spring.datasource.password=ztb
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
6、传统方式pojo-dao(连接mybatis,配置mapper.xml文件)-service-controller
6、使用了mybatis-plus 之后:
创建实体类:
public class User {
    @TableId(type = IdType.AUTO)
    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;
    @Version //乐观锁注解
    private Integer version;
    @TableLogic //逻辑删除
    private Integer deleted;
} //get和set方法,tostring方法,hashcod和equal方法
mapper接口:
// 在对应的Mapper上面继承基本的类 BaseMapper
public interface UserMapper extends BaseMapper<User> {
// 所有的CRUD操作都已经编写完成了
}
要在主启动类上去扫描我们的mapper包下的所有接口:
@MapperScan("com.ztb.mapper")
测试类中测试:
@SpringBootTest
class MybatisplusApplicationTests {
@Resource
private UserMapper userMapper;
@Test
void contextLoads() {
List<User> list = userMapper.selectList(null);
for (User user : list) {
System.out.println(user);
}
}
配置日志:
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
CRUD扩展:
插入操作:
@Test
public void testInsert(){
User user=new User();
user.setName("ztb1");
user.setAge(32);
user.setEmail("9653364@qq,com");
int insert = userMapper.insert(user);
System.out.println(insert);
System.out.println(user);
}
数据库插入的id的默认值为:全局的唯一id
主键生成策略:
分布式系统唯一id生成:https://www.cnblogs.com/haoxinyue/p/5208136.html
雪花算法: snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为 毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味 着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。可以保证几乎全球唯 一!
我们需要在数据库中配置主键自增:
1:
2:在实体类id字段上:
@TableId(type = IdType.AUTO)
private Long id;
3:测试
其余的源码解释
public enum IdType { AUTO(0), // 数据库id自增
NONE(1), // 未设置主键
INPUT(2), // 手动输入
ID_WORKER(3), // 默认的全局唯一id
UUID(4), // 全局唯一id uuid
ID_WORKER_STR(5); //ID_WORKER 字符串表示法 }
更新操作:
@Test
public void testUpdate(){
User user = new User();
user.setId(3L);
user.setAge(444);
int nums = userMapper.updateById(user);
System.out.println(nums);
}
自动填充:
创建时间、修改时间!这些个操作一遍都是自动化完成的,我们不希望手动更新! 阿里巴巴开发手册:所有的数据库表:gmt_create、gmt_modified几乎所有的表都要配置上!而且需 要自动化!
1:在表中新增字段 create_time, update_time:
2、实体类字段属性上需要增加注解
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
3、编写处理器来处理这个注解即可!
@Component
public class MyObjectHnadler 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);
}
}
4、测试插入
5、测试更新、观察时间即可!
乐观锁:
当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:
- 取出记录时,获取当前 version
- 更新时,带上这个 version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果 version 不对,就更新失败
乐观锁:1、先查询,获得版本号 version = 1
-- A
update user set name = "kuangshen", version = version + 1
where id = 2 and version = 1
-- B 线程抢先完成,这个时候 version = 2,会导致 A 修改失败!
update user set name = "kuangshen", version = version + 1
where id = 2 and version = 1
1、给数据库中增加version字段,默认为1
2、实体类加对应的字段:
@Version //乐观锁Version注解
private Integer version;
3、注册组件:新建config包来注册组件:
@Configuration
public class MybatisPlusConfig {
//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
4、测试
@Test //测试乐观锁成功
public void testOLS(){
User user = userMapper.selectById(6L);
user.setEmail("ggsa99@qq.com");
int nums = userMapper.updateById(user);
System.out.println(nums);
}
@Test //测试乐观锁失败
public void testOLF(){
User user = userMapper.selectById(6L);
user.setEmail("ggsa99@qq.com");
User user1 = userMapper.selectById(6L);
user1.setEmail("55555@qq.com");
userMapper.updateById(user1);
userMapper.updateById(user);
}
查询操作:
// 测试查询
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
// 测试批量查询!
@Test
public void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
// 按条件查询之一使用map操作
@Test
public void testSelectByBatchIds(){
HashMap<String, Object> map = new HashMap<>();
// 自定义要查询
map.put("name","Sandy");
map.put("age",21);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
分页查询:
1、原始的 limit 进行分页 2、pageHelper 第三方插件 3、MP 其实也内置了分页插件!
1、配置拦截器组件
@Bean//分页插件
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
2、直接使用Page对象:
@Test//分页
public void testPage(){
//参数一:当前页 参数二:页面大小
Page<User> pa = new Page<>(2, 5);
userMapper.selectPage(pa, null);
for (User record : pa.getRecords()) {
System.out.println(record);
}
System.out.println(pa.getTotal());
}
删除操作:
@Test //删除根据id删除
public void testDelete(){
int nums = userMapper.deleteById(1L);
System.out.println(nums);
}
@Test //批量删除
public void testDeleteBatchId(){
int nums = userMapper.deleteBatchIds(Arrays.asList(5L, 6L));
System.out.println(nums);
}
@Test //根据map、删除
public void testDeleteMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","ztb1");
userMapper.deleteByMap(map);
}
逻辑删除:
物理删除 :从数据库中直接移除
逻辑删除 :再数据库中没有被移除,而是通过一个变量来让他失效! deleted = 0 => deleted = 1
管理员可以查看被删除的记录!防止数据的丢失,类似于回收站!
1、在数据表中增加一个 deleted 字段,默认为0
2、实体类中增加属性
@TableLogic //逻辑删除
private Integer deleted;
3、配置!
@Bean //逻辑删除插件
public ISqlInjector sqlInjector(){
return new LogicSqlInjector();
}
配置文件中:
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
4、测试:
@Test //删除根据id删除
public void testDelete(){
int nums = userMapper.deleteById(1L);
System.out.println(nums);
}
记录依旧在数据库,但是delete值确已经变化了!
再次查询的时候就会过滤掉被逻辑删除的字段
性能分析插件
我们在平时的开发中,会遇到一些慢sql。测试! druid,,,,, 作用:性能分析拦截器,用于输出每条 SQL 语句及其执行时间 MP也提供性能分析插件,如果超过这个时间就停止运行!
1、导入插件:
@Bean //性能分析插件
@Profile({"dev","test"})
public PerformanceInterceptor performanceInterceptor(){
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(150);//设置sql执行的最大时间,如果超过了则不执行
performanceInterceptor.setFormat(true);//是否格式化代码
return performanceInterceptor;
}
记住,要在SpringBoot中配置环境为dev或者 test 环境!:
spring.profiles.active=dev
2、测试:
@Test
void contextLoads() {
List<User> list = userMapper.selectList(null);
for (User user : list) {
System.out.println(user);
}
}

使用性能分析插件,可以帮助我们提高效率
条件构造器:
十分重要:Wrapper
我们写一些复杂的sql就可以使用它来替代!
1:isnotnull,ge:
@Test
void contextLoads() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.isNotNull("name").isNotNull("email").ge("age",21);
List<User> list = userMapper.selectList(wrapper);
for (User user : list) {
System.out.println(user);
}
}

2:eq:
@Test
void test2(){
// 查询名字
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","Tom");
User user = userMapper.selectOne(wrapper); // 查询一个数据,出现多个结果使用List或map
System.out.println(user);
}

3、between:
@Test
void test3(){
// 查询年龄在 20 ~ 30 岁之间的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,30); // 区间
Integer count = userMapper.selectCount(wrapper);// 查询结果数
System.out.println(count);
}

4、notlike、likeright
// 模糊查询
@Test
void test4(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 左和右 t%
wrapper
.notLike("name","e")
.likeRight("email","t");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}
 
5、子查询insql
@Test
void test5(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
// id 在子查询中查出来
wrapper.inSql("id","select id from user where id<3");
List<Object> objects = userMapper.selectObjs(wrapper);
objects.forEach(System.out::println);
}
 
6、orderByAsc:
@Test
void test6(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 通过age进行排序
wrapper.orderByAsc("age");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
 
代码自动生成器:
public static void main(String[] args) {
    //需要构建一个代码自动生成器对象
    AutoGenerator autoGenerator = new AutoGenerator();
    //配置策略
    //1全局配置
    GlobalConfig globalConfig = new GlobalConfig();
    String projectPath= System.getProperty("user.dir");
    globalConfig.setOutputDir("E:\\ChromeGo\\mybatis-plus\\mybatisplus\\src\\main\\java");
    globalConfig.setAuthor("ztb");
    globalConfig.setOpen(false);
    globalConfig.setFileOverride(false);//是否覆盖
    globalConfig.setServiceName("%sService");//去掉service的I前缀
    globalConfig.setIdType(IdType.ID_WORKER);
    globalConfig.setDateType(DateType.ONLY_DATE);
    globalConfig.setSwagger2(true);
    autoGenerator.setGlobalConfig(globalConfig);
    //2设置数据源
    DataSourceConfig dataSourceConfig = new DataSourceConfig();
    dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/store?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8");
    dataSourceConfig.setUsername("root");
    dataSourceConfig.setPassword("ztb");
    dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
    dataSourceConfig.setDbType(DbType.MYSQL);
    autoGenerator.setDataSource(dataSourceConfig);
    //3包的配置
    PackageConfig packageConfig = new PackageConfig();
    packageConfig.setModuleName("store");
    packageConfig.setParent("com.ztb");
    packageConfig.setEntity("entity");
    packageConfig.setMapper("mapper");
    packageConfig.setController("controller");
    packageConfig.setService("service");
    autoGenerator.setPackageInfo(packageConfig);
    //4策略配置
    StrategyConfig strategyConfig = new StrategyConfig();
    strategyConfig.setInclude("t_user","t_address");//设置要映射的表名
    strategyConfig.setNaming(NamingStrategy.underline_to_camel);
    strategyConfig.setEntityLombokModel(false);//不自动lombok
    strategyConfig.setLogicDeleteFieldName("deleted");//逻辑删除
    //自动填充配置
    TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
    TableFill gmtModified = new TableFill("gmt_modified",
            FieldFill.INSERT_UPDATE);
    ArrayList<TableFill> tableFills = new ArrayList<>();
    tableFills.add(gmtCreate);
    tableFills.add(gmtModified);
    strategyConfig.setTableFillList(tableFills);
    // 乐观锁
    strategyConfig.setVersionFieldName("version");
   strategyConfig.setRestControllerStyle(true);
    strategyConfig.setControllerMappingHyphenStyle(true);
    autoGenerator.setStrategy(strategyConfig);
    autoGenerator.execute();//执行
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号