当前位置:   article > 正文

springboot 集成mybatisPlus_mapperscannerconfigure mybatisplus与springboot集成

mapperscannerconfigure mybatisplus与springboot集成

今天整理下自己在整合springboot + mybatisPlus 中遇到的一些小挫折。

项目整体结构图:(请注意:我这里使用的MYSQL 版本为8)


项目整体依赖的pom 文件:

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>com.zzg</groupId>
  7. <artifactId>springboot</artifactId>
  8. <version>0.0.1-SNAPSHOT</version>
  9. </parent>
  10. <artifactId>springboot-mybatisplus</artifactId>
  11. <dependencies>
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-web</artifactId>
  15. </dependency>
  16. <dependency>
  17. <groupId>junit</groupId>
  18. <artifactId>junit</artifactId>
  19. <version>3.8.1</version>
  20. <scope>test</scope>
  21. </dependency>
  22. <!--引入swagger -->
  23. <dependency>
  24. <groupId>io.springfox</groupId>
  25. <artifactId>springfox-swagger2</artifactId>
  26. <version>2.2.2</version>
  27. </dependency>
  28. <dependency>
  29. <groupId>io.springfox</groupId>
  30. <artifactId>springfox-swagger-ui</artifactId>
  31. <version>2.2.2</version>
  32. </dependency>
  33. <!--集成mybatis -->
  34. <!-- 与数据库操作相关的依赖 -->
  35. <dependency>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-starter-jdbc</artifactId>
  38. </dependency>
  39. <!-- 使用数据源 -->
  40. <dependency>
  41. <groupId>com.alibaba</groupId>
  42. <artifactId>druid</artifactId>
  43. <version>1.1.6</version>
  44. </dependency>
  45. <!-- mysql -->
  46. <dependency>
  47. <groupId>mysql</groupId>
  48. <artifactId>mysql-connector-java</artifactId>
  49. <version>8.0.11</version>
  50. </dependency>
  51. <!-- mybatisplus集成 -->
  52. <dependency>
  53. <groupId>com.baomidou</groupId>
  54. <artifactId>mybatisplus-spring-boot-starter</artifactId>
  55. <version>1.0.5</version>
  56. </dependency>
  57. <dependency>
  58. <groupId>com.baomidou</groupId>
  59. <artifactId>mybatis-plus</artifactId>
  60. <version>2.1.8</version>
  61. </dependency>
  62. <!-- mybatisplus 代码生成器 -->
  63. <!-- 模板引擎 -->
  64. <dependency>
  65. <groupId>org.apache.velocity</groupId>
  66. <artifactId>velocity-engine-core</artifactId>
  67. <version>2.0</version>
  68. </dependency>
  69. <!-- 模板引擎,需要指定 mpg.setTemplateEngine(new FreemarkerTemplateEngine()); -->
  70. <dependency>
  71. <groupId>org.freemarker</groupId>
  72. <artifactId>freemarker</artifactId>
  73. <version>2.3.23</version>
  74. </dependency>
  75. </dependencies>
  76. </project>

第一步:集成mybatisplus 核心框架pom.xml

  1. <!--集成mybatis -->
  2. <!-- 与数据库操作相关的依赖 -->
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-jdbc</artifactId>
  6. </dependency>
  7. <!-- mybatisplus集成 -->
  8. <dependency>
  9. <groupId>com.baomidou</groupId>
  10. <artifactId>mybatisplus-spring-boot-starter</artifactId>
  11. <version>1.0.5</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>com.baomidou</groupId>
  15. <artifactId>mybatis-plus</artifactId>
  16. <version>2.1.8</version>
  17. </dependency>
注意: mybatis-plus 自动的维护了mybatis以及mybatis-spring的依赖,在springboot中这三者不能同时的出现,避免版本的冲突,表示:跳进过这个坑。。。

第二步:集成mybatisplus  代码生成器

  1. <!-- mybatisplus 代码生成器 -->
  2. <!-- 模板引擎 -->
  3. <dependency>
  4. <groupId>org.apache.velocity</groupId>
  5. <artifactId>velocity-engine-core</artifactId>
  6. <version>2.0</version>
  7. </dependency>
  8. <!-- 模板引擎,需要指定 mpg.setTemplateEngine(new FreemarkerTemplateEngine()); -->
  9. <dependency>
  10. <groupId>org.freemarker</groupId>
  11. <artifactId>freemarker</artifactId>
  12. <version>2.3.23</version>
  13. </dependency>

编写mybatisplus  自动生成器MybatisPlusGenerator.java(基于单列模式进行创建)

  1. package com.zzg.springboot.auto;
  2. import com.baomidou.mybatisplus.generator.AutoGenerator;
  3. import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
  4. import com.baomidou.mybatisplus.generator.config.GlobalConfig;
  5. import com.baomidou.mybatisplus.generator.config.PackageConfig;
  6. import com.baomidou.mybatisplus.generator.config.StrategyConfig;
  7. import com.baomidou.mybatisplus.generator.config.rules.DbType;
  8. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  9. public class MybatisPlusGenerator {
  10. private static MybatisPlusGenerator single = null;
  11. private MybatisPlusGenerator() {
  12. super();
  13. }
  14. private static MybatisPlusGenerator getSingle() {
  15. if(single == null) {
  16. single =new MybatisPlusGenerator();
  17. }
  18. return single;
  19. }
  20. public void autoGeneration() {
  21. GlobalConfig config = new GlobalConfig();
  22. String dbUrl = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8";
  23. DataSourceConfig dataSourceConfig = new DataSourceConfig();
  24. dataSourceConfig.setDbType(DbType.MYSQL)
  25. .setUrl(dbUrl)
  26. .setUsername("root")
  27. .setPassword("123456")
  28. .setDriverName("com.mysql.cj.jdbc.Driver");
  29. StrategyConfig strategyConfig = new StrategyConfig();
  30. strategyConfig
  31. .setCapitalMode(true)
  32. .setEntityLombokModel(false)
  33. .setDbColumnUnderline(true)
  34. .setNaming(NamingStrategy.underline_to_camel);
  35. config.setActiveRecord(false)
  36. .setEnableCache(false)
  37. .setAuthor("zzg")
  38. //指定输出文件夹位置
  39. .setOutputDir("E:\\workspace\\springboot\\springboot-mybatisplus\\src\\main\\java")
  40. .setFileOverride(true)
  41. .setServiceName("%sService");
  42. new AutoGenerator().setGlobalConfig(config)
  43. .setDataSource(dataSourceConfig)
  44. .setStrategy(strategyConfig)
  45. .setPackageInfo(
  46. new PackageConfig()
  47. .setParent("com.zzg.springboot")
  48. .setController("controller")
  49. .setEntity("entity")
  50. ).execute();
  51. }
  52. public static void main(String[] args) {
  53. // TODO Auto-generated method stub
  54. MybatisPlusGenerator generator = MybatisPlusGenerator.getSingle();
  55. generator.autoGeneration();
  56. }
  57. }

第三步:配置application.properties

  1. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  2. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  3. spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8
  4. spring.datasource.username=root
  5. spring.datasource.password=123456
  6. spring.datasource.initialSize=5
  7. spring.datasource.minIdle=5
  8. spring.datasource.maxActive=20
  9. spring.datasource.maxWait=60000
  10. spring.datasource.timeBetweenEvictionRunsMillis=60000
  11. spring.datasource.minEvictableIdleTimeMillis=300000
  12. spring.datasource.validationQuery=SELECT 1 FROM DUAL
  13. spring.datasource.testWhileIdle=true
  14. spring.datasource.testOnBorrow=false
  15. spring.datasource.testOnReturn=false
  16. spring.datasource.poolPreparedStatements=true
  17. spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
  18. spring.datasource.filters=stat,wall,log4j
  19. spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  20. mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
  21. mybatis-plus.typeAliasesPackage=com.zzg.springboot.entity

第四步:项目的配置信息

  1. package com.zzg.springboot.config;
  2. import javax.sql.DataSource;
  3. import org.mybatis.spring.annotation.MapperScan;
  4. import org.mybatis.spring.mapper.MapperScannerConfigurer;
  5. import org.springframework.boot.context.properties.ConfigurationProperties;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  9. import com.alibaba.druid.pool.DruidDataSource;
  10. import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
  11. import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
  12. @Configuration
  13. //扫描dao或者是Mapper接口
  14. @MapperScan("com.zzg.springboot.mapper*")
  15. public class MybatisPlusConfig {
  16. /***
  17. * plus 的性能优化
  18. * @return
  19. */
  20. @Bean
  21. public PerformanceInterceptor performanceInterceptor() {
  22. PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
  23. /*<!-- SQL 执行性能分析,开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 -->*/
  24. performanceInterceptor.setMaxTime(1000);
  25. /*<!--SQL是否格式化 默认false-->*/
  26. performanceInterceptor.setFormat(true);
  27. return performanceInterceptor;
  28. }
  29. /**
  30. * @Description : mybatis-plus分页插件
  31. */
  32. @Bean
  33. public PaginationInterceptor paginationInterceptor() {
  34. return new PaginationInterceptor();
  35. }
  36. // 配置数据源
  37. @Bean(name="dataSource")
  38. @ConfigurationProperties(prefix="spring.datasource")
  39. public DataSource dataSource(){
  40. return new DruidDataSource();
  41. }
  42. // 配置事物管理器
  43. @Bean(name="transactionManager")
  44. public DataSourceTransactionManager transactionManager(){
  45. return new DataSourceTransactionManager(dataSource());
  46. }
  47. }

第五步:启动springbootApplication

  1. package com.zzg.springboot;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class SpringBootMybatisPlus {
  6. public static void main(String[] args) {
  7. // TODO Auto-generated method stub
  8. SpringApplication.run(SpringBootMybatisPlus.class, args);
  9. System.out.println("============= SpringBoot web Start Success =============");
  10. }
  11. }

项目关联的entity层、dao层、service层、controller层和*Mapper.xml文件

  1. package com.zzg.springboot.entity;
  2. import com.baomidou.mybatisplus.enums.IdType;
  3. import com.baomidou.mybatisplus.annotations.TableId;
  4. import java.io.Serializable;
  5. /**
  6. * <p>
  7. * 学员表
  8. * </p>
  9. *
  10. * @author zzg123
  11. * @since 2018-07-15
  12. */
  13. public class TStudent implements Serializable {
  14. private static final long serialVersionUID = 1L;
  15. @TableId(value = "sid", type = IdType.AUTO)
  16. private Integer sid;
  17. private String sname;
  18. private String sex;
  19. public Integer getSid() {
  20. return sid;
  21. }
  22. public void setSid(Integer sid) {
  23. this.sid = sid;
  24. }
  25. public String getSname() {
  26. return sname;
  27. }
  28. public void setSname(String sname) {
  29. this.sname = sname;
  30. }
  31. public String getSex() {
  32. return sex;
  33. }
  34. public void setSex(String sex) {
  35. this.sex = sex;
  36. }
  37. @Override
  38. public String toString() {
  39. return "TStudent{" +
  40. ", sid=" + sid +
  41. ", sname=" + sname +
  42. ", sex=" + sex +
  43. "}";
  44. }
  45. }
  1. package com.zzg.springboot.mapper;
  2. import java.util.Map;
  3. import com.baomidou.mybatisplus.mapper.BaseMapper;
  4. import com.zzg.springboot.entity.TStudent;
  5. /**
  6. * <p>
  7. * 学员表 Mapper 接口
  8. * </p>
  9. *
  10. * @author zzg123
  11. * @since 2018-07-15
  12. */
  13. public interface TStudentMapper extends BaseMapper<TStudent> {
  14. /**
  15. *
  16. * @Title: selectUserByMap
  17. * @Description: 多条件组合查找用户
  18. * @param userId
  19. * @return
  20. * @throws Exception
  21. */
  22. TStudent selectUserByMap(Map<String, Object> parameterMap) throws Exception;
  23. }

  1. package com.zzg.springboot.service;
  2. import java.util.Map;
  3. import com.baomidou.mybatisplus.service.IService;
  4. import com.zzg.springboot.entity.TStudent;
  5. /**
  6. * <p>
  7. * 学员表 服务类
  8. * </p>
  9. *
  10. * @author zzg123
  11. * @since 2018-07-15
  12. */
  13. public interface TStudentService extends IService<TStudent> {
  14. /**
  15. *
  16. * @Title: selectUserByMap
  17. * @Description: 多条件组合查找用户
  18. * @param userId
  19. * @return
  20. * @throws Exception
  21. */
  22. TStudent selectUserByMap(Map<String, Object> parameterMap) throws Exception;
  23. }

  1. package com.zzg.springboot.service.impl;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import javax.annotation.Resource;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import com.baomidou.mybatisplus.service.impl.ServiceImpl;
  8. import com.zzg.springboot.entity.TStudent;
  9. import com.zzg.springboot.mapper.TStudentMapper;
  10. import com.zzg.springboot.service.TStudentService;
  11. /**
  12. * <p>
  13. * 学员表 服务实现类
  14. * </p>
  15. *
  16. * @author zzg123
  17. * @since 2018-07-15
  18. */
  19. @Service
  20. public class TStudentServiceImpl extends ServiceImpl<TStudentMapper, TStudent> implements TStudentService {
  21. /**
  22. * 用户数据访问接口
  23. */
  24. @Resource
  25. private TStudentMapper tstudentMapper;
  26. @Override
  27. public TStudent selectUserByMap(Map<String, Object> parameterMap) throws Exception {
  28. // TODO Auto-generated method stub
  29. return tstudentMapper.selectUserByMap(parameterMap);
  30. }
  31. }

  1. package com.zzg.springboot.controller;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import javax.annotation.Resource;
  5. import javax.servlet.http.HttpServletRequest;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10. import com.zzg.springboot.entity.TStudent;
  11. import com.zzg.springboot.service.TStudentService;
  12. /**
  13. * <p>
  14. * 学员表 前端控制器
  15. * </p>
  16. *
  17. * @author zzg123
  18. * @since 2018-07-15
  19. */
  20. @Controller
  21. @RequestMapping("/tStudent")
  22. public class TStudentController {
  23. @Resource
  24. private TStudentService service;
  25. @RequestMapping("/get")
  26. @ResponseBody
  27. public TStudent get(HttpServletRequest request, Model model) throws Exception {
  28. Map<String, Object> map = new HashMap<String, Object>();
  29. map.put("sid", 1);
  30. TStudent student = this.service.selectUserByMap(map);
  31. return student;
  32. }
  33. }

建库脚本:

  1. CREATE TABLE `t_student` (
  2. `sid` INT(11) NOT NULL AUTO_INCREMENT,
  3. `sname` VARCHAR(255) NULL DEFAULT '0',
  4. `sex` CHAR(2) NULL DEFAULT '0',
  5. PRIMARY KEY (`sid`)
  6. )
  7. COMMENT='学员表'
  8. COLLATE='utf8mb4_0900_ai_ci'
  9. ENGINE=InnoDB
MyBatisPlus官网学习地址: http://mp.baomidou.com/#/install


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/319718
推荐阅读
相关标签
  

闽ICP备14008679号