码迷,mamicode.com
首页 > 其他好文 > 详细

mybatis plus的逆向工程及基本使用

时间:2020-07-07 09:53:07      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:hide   com   bee   jdbc   temp   red   初始   cci   依赖   

yml的配置

mybatis-plus:
  mapper-locations: classpath*:com/gwq/movie/**/xml/*Mapper.xml
  global-config:
    id-type: 0
    db-column-underline: false
    refresh-mapper: true

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/meetingfilm?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=UTC
    username: root
    password: root
    filters: log4j,wall,mergeStat

俩个配置类

技术图片
package com.next.jiangzh.springbootdemo.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLException;

@Data
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidProperties {

    private String url = "jdbc:mysql://127.0.0.1:3306/mooc_demo?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=UTC";

    private String username = "root";

    private String password = "1234567";

    private String driverClassName = "com.mysql.cj.jdbc.Driver";

    private Integer initialSize = 2;

    private Integer minIdle = 1;

    private Integer maxActive = 20;

    private Integer maxWait = 60000;

    private Integer timeBetweenEvictionRunsMillis = 60000;

    private Integer minEvictableIdleTimeMillis = 300000;

    private String validationQuery = "SELECT ‘x‘";

    private Boolean testWhileIdle = true;

    private Boolean testOnBorrow = false;

    private Boolean testOnReturn = false;

    private Boolean poolPreparedStatements = true;

    private Integer maxPoolPreparedStatementPerConnectionSize = 20;

    private String filters = "stat";

    public void config(DruidDataSource dataSource) {

        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        dataSource.setDriverClassName(driverClassName);
        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);

        // 打开PSCache,并且指定每个连接上PSCache的大小
        dataSource.setPoolPreparedStatements(poolPreparedStatements);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);

        try {
            dataSource.setFilters(filters);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
DruidProperties
技术图片
package com.next.jiangzh.springbootdemo.config;


import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = {"com.mooc.jiangzh.springbootdemo.dao.mapper"})
public class MybatisPlusConfig {

    @Bean
    public DruidDataSource dataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = new DruidDataSource();
        druidProperties.config(dataSource);
        return dataSource;
    }

    /**
     * mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /**
     * 乐观锁mybatis插件
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }


}
MybatisPlusConfig

一个自动生成类

技术图片
package com.next.jiangzh.springbootdemo;


import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.BeetlTemplateEngine;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/*
    数据层内容生成
 */
public class EntityGenerator {

    // 生成输出目录,定位到工程的java目录下
    private String outputDir = "F:\\workSpace\\mooc_workspace\\demo_workspace\\springboot-demo\\src\\main\\java";
    // 生成类的作者
    private String author = "jiangzh";
    // 数据源相关配置
    private String url = "jdbc:mysql://127.0.0.1:3306/mooc_demo?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=UTC";
    private String driverName = "com.mysql.cj.jdbc.Driver";
    private String userName = "root";
    private String userPwd = "123456";
    // DAO的包路径
    private String daoPackage = "com.mooc.jiangzh.springbootdemo.dao";
    // 待生成的表名,注意是覆盖更新
    private static String[] tableNames;

    static{
        tableNames = new String[]{
                "mooc_user"
        };
    }

    @Test
    public void entityGenerator() {
        AutoGenerator mpg = new AutoGenerator();
        mpg.setTemplateEngine(new BeetlTemplateEngine());
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(outputDir);
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        gc.setEnableCache(false);
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(false);
        gc.setAuthor(author);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(url);
        // dsc.setSchemaName("public");
        dsc.setDriverName(driverName);
        dsc.setUsername(userName);
        dsc.setPassword(userPwd);
        mpg.setDataSource(dsc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        //strategy.setTablePrefix(new String[]{"_"});// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(tableNames);
        mpg.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(null);
        pc.setEntity(daoPackage+".entity");
        pc.setMapper(daoPackage+".mapper");
        pc.setXml(daoPackage+".mapper.xml");
        mpg.setPackageInfo(pc);

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };

        mpg.setCfg(cfg);

        // 执行生成
        mpg.execute();

        // 打印注入设置
        System.err.println(mpg.getCfg().getMap().get("abc"));

    }

}
EntityGenerator

相关依赖

技术图片
<!-- mybatis-plus依赖 -->
  <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>${mybatis.plus.version}</version>
  </dependency>

  <!-- Druid引入 -->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>${druid.version}</version>
  </dependency>

  <!-- 数据源驱动 -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
  </dependency>

  <!-- 代码生成器依赖 -->
  <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>${mybatis.plus.version}</version>
  </dependency>

  <dependency>
    <groupId>com.ibeetl</groupId>
    <artifactId>beetl</artifactId>
    <version>${beetl.version}</version>
  </dependency>
View Code

资源引入依赖,不引入放在src/main/java下的xml不识别

<!-- 资源引入 -->
<resources>
    <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
    </resource>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
</resources>

分页演示:

controller实现层

技术图片
    @RequestMapping(value = "",method = RequestMethod.GET)
    public BaseResponseVo findCinemaList(BasePageVO page) throws CommonServiceException{
        IPage<CinemaReqVo> moocCinemaTIPage = cinemaService.findAllCinema(page.getNowPage(),page.getPageSize());
        Map<String,Object> all = getResultMap(moocCinemaTIPage,"cinemas");
        return BaseResponseVo.success(all);
    }

    public Map<String,Object> getResultMap(IPage page,String title){
        Map<String,Object> map = new HashMap<>();
        map.put("totalSize",page.getTotal());
        map.put("totalPages",page.getPages());
        map.put("pageSize",page.getSize());
        map.put("nowPage",page.getCurrent());
        map.put(title,page.getRecords());
        return map;
    }
View Code

Service层

 IPage<CinemaReqVo> findAllCinema(int currentPage,int PageSize) throws CommonServiceException;

impl层

 public IPage<CinemaReqVo> findAllCinema(int currentPage,int PageSize) throws CommonServiceException {
          return cinemaTMapper.findAllCinema(new Page<>(currentPage,PageSize));
    }

dao层

  IPage<CinemaReqVo>  findAllCinema(Page<CinemaReqVo> page);

mapper

技术图片
   <select id="findAllCinema" resultType="com.gwq.movie.backendcinema.controller.vo.CinemaReqVo">
        select brand_id as brandId,
               area_id as areaId,
               hall_ids as hallTypeIds,
               cinema_name as cinemaName,
               cinema_address as cinemaAddress,
               cinema_phone as cinemaTele,
               img_address as cinemaImgAddress,
               minimum_price as cinemaPrice
        from mooc_cinema_t
    </select>
View Code

 

mybatis plus的逆向工程及基本使用

标签:hide   com   bee   jdbc   temp   red   初始   cci   依赖   

原文地址:https://www.cnblogs.com/ghwq/p/13258828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!