11.Springboot集成mybatis-plus

在Springboot大行其道的时代,任何关于框架的集成都少不了Springboot。

一、创建maven工程并导入相应的包


    4.0.0
    com.qiu
    mybatisplus-springboot
    0.0.1-SNAPSHOT
    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.0.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
    
        
            log4j
            log4j
            1.2.17
        

        
        
            com.alibaba
            fastjson
            1.2.49
        

        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        

        
            org.springframework.boot
            spring-boot-starter
        

        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        

        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-devtools
            runtime
        
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            com.baomidou
            mybatis-plus
            2.3
        

        
            com.baomidou
            mybatisplus-spring-boot-starter
            1.0.5
        

        
        
            org.apache.velocity
            velocity
            1.7
        

        
        
            com.alibaba
            druid
            1.0.28
        

    


二、通过mybatis-plus代码生成器生成相应的代码

  • 这里参考spring集成mybatis-plus这篇博客有关代码生成器部分
  • 这里需要注意的是需要在Mapper接口上加上注解@Mapper,Springboot才可以扫描的到。
@Mapper
public interface UserMapper extends BaseMapper {

}

三、代码生成器中生成的UserService和实现类

  • UserService
public interface UserService extends IService {   
}
  • UserServiceImpl
//由于这里继承ServiceImpl,而这个类导入了UserMapper,因此无需再导入Mapper就可以开发了
@Service
public class UserServiceImpl extends ServiceImpl 
implements UserService {
    
}

四、UserController

@RestController
@RequestMapping("/user")
public class UserController {
    //注入UserService 接口
    @Autowired
    private UserService userService;
    @RequestMapping("/getAllUsers")
    public String getAllUsers() {
                //获取全部列表
        List selectList = userService.selectList(null);
        return JSON.toJSONString(selectList);
    }
    @RequestMapping("/delete/{id}")
    public String deleteUserById(@PathVariable(name="id")Integer id) {
                 //根据id删除
        boolean deleteById = userService.deleteById(id);
        return deleteById==true?"删除成功":"删除失败";
        
    }
    
}

五、Springboot相关配置

  • druid数据源配置
@Configuration
public class DruidDataSourceConfig {
    private Logger logger = LoggerFactory.getLogger(DruidDataSourceConfig.class);

    @Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;

    @Value("${spring.datasource.initialSize}")
    private int initialSize;

    @Value("${spring.datasource.minIdle}")
    private int minIdle;

    @Value("${spring.datasource.maxActive}")
    private int maxActive;

    @Value("${spring.datasource.maxWait}")
    private int maxWait;

    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;

    @Value("${spring.datasource.testWhileIdle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.testOnReturn}")
    private boolean testOnReturn;

    @Value("${spring.datasource.poolPreparedStatements}")
    private boolean poolPreparedStatements;

    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
    private int maxPoolPreparedStatementPerConnectionSize;

    @Value("${spring.datasource.filters}")
    private String filters;

    @Value("{spring.datasource.connectionProperties}")
    private String connectionProperties;

    @Bean     //声明其为Bean实例
    @Primary  //在同样的DataSource中,首先使用被标注的DataSource
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();

        datasource.setUrl(this.dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);

        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            logger.error("druid configuration initialization filter : {0}", e);
        }
        datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }
    
}
  • mybatis-plus相关配置(分页插件和性能优化)
@Configuration
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType("mysql");
        return page;
    }
      /***
     * plus 的性能优化
     * @return
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        /**/
        performanceInterceptor.setMaxTime(1000);
        /**/
        performanceInterceptor.setFormat(true);
        return performanceInterceptor;
    }
}
  • application.properties(Springboot配置文件)```
server.port=8082
# jdbc_config
# 驱动配置信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/mybatis
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver

# 连接池的配置信息
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000



#mybatisplus
#配置文件位置
#mybatis-plus.config-location=
#mapper文件文职
mybatis-plus.mapper-locations=classpath:mapper/*.xml
#设置别名的包名
mybatis-plus.type-aliases-package=com.、qiu.entity
##主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
mybatis-plus.global-config.id-type=0
##字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
mybatis-plus.global-config.field-strategy=0
# #驼峰下划线转换
mybatis-plus.global-config.db-column-underline=true
#刷新mapper 调试神器
mybatis-plus.global-config.refresh-mapper=true
#数据库大写下划线转换
#mybatis-plus.global-config.capital-mode=true
 #序列接口实现类配置
#mybatis-plus.global-config.key-generator=com.baomidou.springboot.xxx
 #逻辑删除配置(下面3个配置)
mybatis-plus.global-config.logic-delete-value=0
mybatis-plus.global-config.logic-not-delete-value=1
#自定义SQL注入器
3mybatis-plus.global-config.sql-injector=com.baomidou.mybatisplus.mapper.LogicSqlInjector
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.configuration.cache-enabled=false

六、Springboot启动类

@SpringBootApplication
public class MybatisPlusApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusApplication.class, args);
    }
}

你可能感兴趣的:(11.Springboot集成mybatis-plus)