MyBatis Plus逻辑删除和分页插件使用详解
概要:Mybatisplus官网链接:https://mp.baomidou.com/guide/
一、依赖配置:
4.0.0 org.springframework.boot spring-boot-starter-parent 2.2.6.RELEASE com.example demo 0.0.1-SNAPSHOT demo DemoprojectforSpringBoot 1.8 org.springframework.boot spring-boot-starter-web mysql mysql-connector-java runtime org.projectlombok lombok true com.baomidou mybatisplus-spring-boot-starter 1.0.5 org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine com.baomidou mybatis-plus 3.3.1 org.springframework.boot spring-boot-maven-plugin
二、数据源和插件相关配置
-application.yml
server: port:8080 servlet: context-path:/ #LoggerConfig logging: level: com.baomidou.mybatisplus.samples.quickstart:debug
-db.properties
spring.datasource.jdbc-url=jdbc:mysql://localhost:3306/demo?serverTimezone=UTC&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
-MybatisPlusConfig
packagecom.example.demo.config; importcom.baomidou.mybatisplus.annotation.DbType; importcom.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; importcom.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize; importorg.mybatis.spring.annotation.MapperScan; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.transaction.annotation.EnableTransactionManagement; @EnableTransactionManagement @Configuration @MapperScan("com.example.demo.mapper") publicclassMybatisPlusConfig{ @Bean("paginationInterceptor") publicPaginationInterceptorpaginationInterceptor(){ PaginationInterceptorpaginationInterceptor=newPaginationInterceptor(); paginationInterceptor.setCountSqlParser(newJsqlParserCountOptimize(true)); paginationInterceptor.setDbType(DbType.MYSQL); returnpaginationInterceptor; } }
-SqlSessionConfig
packagecom.example.demo.config; importcom.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; importcom.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean; importorg.apache.ibatis.plugin.Interceptor; importorg.mybatis.spring.mapper.MapperScannerConfigurer; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.beans.factory.annotation.Qualifier; importorg.springframework.boot.context.properties.ConfigurationProperties; importorg.springframework.boot.jdbc.DataSourceBuilder; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.context.annotation.PropertySource; importorg.springframework.core.io.support.PathMatchingResourcePatternResolver; importjavax.sql.DataSource; @Configuration @PropertySource("classpath:db/db.properties") publicclassSqlSessionConfig{ privateLoggerlogger=LoggerFactory.getLogger(SqlSessionConfig.class); @Bean("myDatasource") @ConfigurationProperties(prefix="spring.datasource") publicDataSourcemasterDataSource(){ returnDataSourceBuilder.create().build(); } @Bean("mySqlSessionFactoryBean") publicMybatisSqlSessionFactoryBeancreateSqlSessionFactory(@Qualifier("myDatasource")DataSourcedataSource, @Qualifier("paginationInterceptor")PaginationInterceptorpaginationInterceptor){ //MybatisSqlSessionFactory MybatisSqlSessionFactoryBeansqlSessionFactoryBean=null; try{ //实例SessionFactory sqlSessionFactoryBean=newMybatisSqlSessionFactoryBean(); //配置数据源 sqlSessionFactoryBean.setDataSource(dataSource); //设置MyBatis-Plus分页插件 Interceptor[]plugins={paginationInterceptor}; sqlSessionFactoryBean.setPlugins(plugins); //加载MyBatis配置文件 PathMatchingResourcePatternResolverresourcePatternResolver=newPathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath*:mapper/*.xml")); }catch(Exceptione){ logger.error("InitSqlSessionFactoryError:{}",e.getMessage()); } returnsqlSessionFactoryBean; } @Bean publicMapperScannerConfigurermyGetMapperScannerConfigurer(){ MapperScannerConfigurermyMapperScannerConfigurer=newMapperScannerConfigurer(); myMapperScannerConfigurer.setBasePackage("com.example.demo.mapper"); myMapperScannerConfigurer.setSqlSessionFactoryBeanName("mySqlSessionFactoryBean"); returnmyMapperScannerConfigurer; } }
三、测试类
-UserController
packagecom.example.demo.controller; importcom.baomidou.mybatisplus.extension.plugins.pagination.Page; importcom.example.demo.bean.UserDTO; importcom.example.demo.entity.User; importcom.example.demo.service.UserService; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.web.bind.annotation.RequestBody; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RequestMethod; importorg.springframework.web.bind.annotation.RestController; importjava.time.LocalDateTime; importjava.util.List; @RestController @RequestMapping(value="/demo") publicclassUserController{ @Autowired privateUserServiceuserService; @RequestMapping(value="/create",method=RequestMethod.POST) publicStringcreate(@RequestBodyUserDTOuserDTO){ Useruser=newUser(); user.setName(userDTO.getName()); user.setPhone(userDTO.getPhone()); user.setCreateTime(LocalDateTime.now()); user.setEnable(true); user.setVersion(1L); userService.insert(user); return"ok"; } @RequestMapping(value="/delete",method=RequestMethod.POST) publicStringcreate(Longid){ userService.deleteById(id); return"ok"; } @RequestMapping(value="/update",method=RequestMethod.POST) publicStringupdate(@RequestBodyUserDTOuserDTO){ Useruser=newUser(); user.setId(userDTO.getId()); user.setName(userDTO.getName()); user.setPhone(userDTO.getPhone()); user.setCreateTime(LocalDateTime.now()); userService.updateById(user); return"ok"; } @RequestMapping(value="/queryPage",method=RequestMethod.POST) publicListupdate(IntegerpageNo,IntegerpageSize){ Page page=newPage<>(pageNo,pageSize); returnuserService.queryList(page,1); } }
-UserService
packagecom.example.demo.service.impl; importcom.baomidou.mybatisplus.core.metadata.IPage; importcom.baomidou.mybatisplus.extension.plugins.pagination.Page; importcom.example.demo.mapper.UserMapper; importcom.example.demo.entity.User; importcom.example.demo.service.UserService; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.stereotype.Service; importjava.util.List; importjava.util.Optional; @Service publicclassUserServiceImplimplementsUserService{ @Autowired privateUserMapperuserMapper; @Override publicintinsert(Useruser){ returnuserMapper.insert(user); } @Override publicintdeleteById(Longid){ returnuserMapper.deleteById(id); } @Override publicintupdateById(Useruser){ returnuserMapper.updateById(user); } @Override publicListqueryList(Page page,Integerenable){ returnuserMapper.selectPageByEnable(page,enable).getRecords(); } }
-UserMapper
packagecom.example.demo.mapper; importcom.baomidou.mybatisplus.core.mapper.BaseMapper; importcom.baomidou.mybatisplus.core.metadata.IPage; importcom.baomidou.mybatisplus.extension.plugins.pagination.Page; importcom.example.demo.entity.User; importorg.apache.ibatis.annotations.Mapper; importorg.springframework.stereotype.Repository; @Mapper @Repository publicinterfaceUserMapperextendsBaseMapper{ IPage selectPageByEnable(Page>page,Integerenable); }
-User
packagecom.example.demo.entity; importcom.baomidou.mybatisplus.annotation.*; importlombok.Data; importjava.time.LocalDateTime; @Data @TableName("user") publicclassUser{ @TableId(value="id",type=IdType.AUTO) privateLongid; @TableField("name") privateStringname; @TableField("phone") privateStringphone; @TableField("create_time") privateLocalDateTimecreateTime; @TableLogic(delval="0",value="1") @TableField("enable") privatebooleanenable; @Version @TableField("version") privateLongversion; }
-SqlMap
SELECT*FROMuserWHEREenable=#{enable}orderbycreate_timedesc
-DDL
CREATETABLE`user`( `id`bigintNOTNULLAUTO_INCREMENT, `name`varchar(20)NOTNULL, `phone`char(11)CHARACTERSETutf8mb4COLLATEutf8mb4_0900_ai_ciNOTNULL, `enable`tinyintNOTNULL, `create_time`datetimeNOTNULL, `version`bigintNOTNULL, PRIMARYKEY(`id`) )ENGINE=InnoDBAUTO_INCREMENT=3DEFAULTCHARSET=utf8mb4COLLATE=utf8mb4_0900_ai_ci;
到此这篇关于MyBatisPlus之逻辑删除和分页插件使用的文章就介绍到这了,更多相关MyBatisPlus逻辑删除内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!