概要:Mybatis plus 官网链接 :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 Demo project for Spring Boot 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: / # Logger Config 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
package com.example.demo.config; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableTransactionManagement @Configuration @MapperScan("com.example.demo.mapper") public class MybatisPlusConfig { @Bean("paginationInterceptor") public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true)); paginationInterceptor.setDbType(DbType.MYSQL); return paginationInterceptor; } }
- SqlSessionConfig
package com.example.demo.config; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean; import org.apache.ibatis.plugin.Interceptor; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.sql.DataSource; @Configuration @PropertySource("classpath:db/db.properties") public class SqlSessionConfig { private Logger logger = LoggerFactory.getLogger(SqlSessionConfig.class); @Bean("myDatasource") @ConfigurationProperties(prefix="spring.datasource") public DataSource masterDataSource() { return DataSourceBuilder.create().build(); } @Bean("mySqlSessionFactoryBean") public MybatisSqlSessionFactoryBean createSqlSessionFactory(@Qualifier("myDatasource") DataSource dataSource, @Qualifier("paginationInterceptor") PaginationInterceptor paginationInterceptor) { // MybatisSqlSessionFactory MybatisSqlSessionFactoryBean sqlSessionFactoryBean = null; try { // 实例SessionFactory sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean(); // 配置数据源 sqlSessionFactoryBean.setDataSource(dataSource); // 设置 MyBatis-Plus 分页插件 Interceptor [] plugins = {paginationInterceptor}; sqlSessionFactoryBean.setPlugins(plugins); // 加载MyBatis配置文件 PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath*:mapper/*.xml")); } catch (Exception e) { logger.error("Init SqlSessionFactory Error:{}", e.getMessage()); } return sqlSessionFactoryBean; } @Bean public MapperScannerConfigurer myGetMapperScannerConfigurer() { MapperScannerConfigurer myMapperScannerConfigurer = new MapperScannerConfigurer(); myMapperScannerConfigurer.setBasePackage("com.example.demo.mapper"); myMapperScannerConfigurer.setSqlSessionFactoryBeanName("mySqlSessionFactoryBean"); return myMapperScannerConfigurer; } }
三、测试类
- UserController
package com.example.demo.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.example.demo.bean.UserDTO; import com.example.demo.entity.User; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.time.LocalDateTime; import java.util.List; @RestController @RequestMapping(value = "/demo") public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/create", method = RequestMethod.POST) public String create(@RequestBody UserDTO userDTO){ User user = new User(); 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) public String create(Long id){ userService.deleteById(id); return "ok"; } @RequestMapping(value = "/update", method = RequestMethod.POST) public String update(@RequestBody UserDTO userDTO){ User user = new User(); 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) public Listupdate(Integer pageNo, Integer pageSize){ Page page = new Page<>(pageNo, pageSize); return userService.queryList(page, 1); } }
- UserService
package com.example.demo.service.impl; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.example.demo.mapper.UserMapper; import com.example.demo.entity.User; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public int insert(User user) { return userMapper.insert(user); } @Override public int deleteById(Long id) { return userMapper.deleteById(id); } @Override public int updateById(User user) { return userMapper.updateById(user); } @Override public ListqueryList(Page page, Integer enable) { return userMapper.selectPageByEnable(page, enable).getRecords(); } }
- UserMapper
package com.example.demo.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.example.demo.entity.User; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; @Mapper @Repository public interface UserMapper extends BaseMapper{ IPage selectPageByEnable(Page> page, Integer enable); }
- User
package com.example.demo.entity; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.time.LocalDateTime; @Data @TableName("user") public class User{ @TableId(value = "id", type = IdType.AUTO) private Long id; @TableField("name") private String name; @TableField("phone") private String phone; @TableField("create_time") private LocalDateTime createTime; @TableLogic(delval = "0", value = "1") @TableField("enable") private boolean enable; @Version @TableField("version") private Long version; }
- SqlMap
- DDL
CREATE TABLE `user` ( `id` bigint NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL, `phone` char(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, `enable` tinyint NOT NULL, `create_time` datetime NOT NULL, `version` bigint NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
到此这篇关于MyBatis Plus之逻辑删除和分页插件使用的文章就介绍到这了,更多相关MyBatis Plus逻辑删除内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!