zoukankan      html  css  js  c++  java
  • springboot mybatisPlus配置

    1.pom依赖

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.5.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.*</groupId>
        <artifactId>bus</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>bus</name>
        <description></description>
    
        <properties>
            <java.version>1.8</java.version>
            <qiniu.version>[7.2.0, 7.2.99]</qiniu.version>
            <mybatisplus.spring.boot.version>1.0.5</mybatisplus.spring.boot.version>
            <mybatisplus.version>2.2.0</mybatisplus.version>
            <druid.version>1.1.10</druid.version>
    
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <exclusions>
                    <exclusion>
                        <artifactId>jackson-databind</artifactId>
                        <groupId>com.fasterxml.jackson.core</groupId>
                    </exclusion>
                    <exclusion>
                        <artifactId>slf4j-api</artifactId>
                        <groupId>org.slf4j</groupId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-aop</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>com.qiniu</groupId>
                <artifactId>qiniu-java-sdk</artifactId>
                <version>${qiniu.version}</version>
            </dependency>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatisplus-spring-boot-starter</artifactId>
                <version>${mybatisplus.spring.boot.version}</version>
            </dependency>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus</artifactId>
                <version>${mybatisplus.version}</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>${druid.version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>1.7.19</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity -->
            <dependency>
                <groupId>org.apache.velocity</groupId>
                <artifactId>velocity</artifactId>
                <version>1.7</version>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <fork>true</fork>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    </project>

    2.配置数据源:

    
    
    mybatis-plus:

    mapper-locations: classpath:mapper/*.xml
    #实体扫描,多个package用逗号或者分号分隔
    typeAliasesPackage: com.*.*.entity
    global-config:
    #主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 0
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 1
    sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector

    configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
    #配置JdbcTypeForNull
    jdbc-type-for-null: 'null'
    call-setters-on-nulls: true

    spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driverClassName: com.mysql.jdbc.Driver druid: first: #数据源1 url: jdbc:mysql://:3306/fast?allowMultiQueries=true
    &useUnicode=true&characterEncoding=UTF-8 username: password: second: #数据源2 url: jdbc:mysql://localhost:3306/fast?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8 username: password: initial-size: 10 max-active: 100 min-idle: 10 max-wait: 60000 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 #validation-query: SELECT 1 FROM DUAL test-while-idle: true test-on-borrow: false test-on-return: false stat-view-servlet: enabled: true url-pattern: /druid/* #login-username: admin #login-password: admin filter: stat: log-slow-sql: true slow-sql-millis: 1000 merge-sql: false wall: config: multi-statement-allow: true
    
    
    public interface DataSourceNames {
        String FIRST = "first";
        String SECOND = "second";
    }
    
    import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
    
    import javax.sql.DataSource;
    import java.util.Map;
    
    /**
     * 动态数据源
     */
    public class DynamicDataSource extends AbstractRoutingDataSource {
        private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
    
        public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
            super.setDefaultTargetDataSource(defaultTargetDataSource);
            super.setTargetDataSources(targetDataSources);
            super.afterPropertiesSet();
        }
    
        @Override
        protected Object determineCurrentLookupKey() {
            return getDataSource();
        }
    
        public static void setDataSource(String dataSource) {
            contextHolder.set(dataSource);
        }
    
        public static String getDataSource() {
            return contextHolder.get();
        }
    
        public static void clearDataSource() {
            contextHolder.remove();
        }
    
    }
    import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    
    import javax.sql.DataSource;
    import java.util.HashMap;
    import java.util.Map;
    
    
    @Configuration
    public class DynamicDataSourceConfig {
    
        @Bean
        @ConfigurationProperties("spring.datasource.druid.first")
        public DataSource firstDataSource(){
            return DruidDataSourceBuilder.create().build();
        }
    
        @Bean
        @ConfigurationProperties("spring.datasource.druid.second")
        public DataSource secondDataSource(){
            return DruidDataSourceBuilder.create().build();
        }
    
        @Bean
        @Primary
        public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource) {
            Map<Object, Object> targetDataSources = new HashMap<>();
            targetDataSources.put(DataSourceNames.FIRST, firstDataSource);
            targetDataSources.put(DataSourceNames.SECOND, secondDataSource);
            return new DynamicDataSource(firstDataSource, targetDataSources);
        }
    }

    3.根据表自动生成代码

    import com.baomidou.mybatisplus.generator.AutoGenerator;
    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.DbType;
    import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
    
    
    public class Generator {
    
        public static void main(String[] args) {
            String packageName = "com.*.*";
            boolean serviceNameStartWithI = false;//auth -> UserService, 设置成true: auth -> IUserService
            generateByTables(serviceNameStartWithI, packageName, "saytime", "fast", "user");
    
            System.out.println("completed...");
        }
    
    
        private static void generateByTables(boolean serviceNameStartWithI, String packageName, String author, String database, String... tableNames) {
            GlobalConfig config = new GlobalConfig();
            String dbUrl = "jdbc:mysql://*:3306/" + database + "?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false";
            DataSourceConfig dataSourceConfig = new DataSourceConfig();
            dataSourceConfig.setDbType(DbType.MYSQL)
                    .setUrl(dbUrl)
                    .setUsername("")
                    .setPassword("")
                    .setDriverName("com.mysql.jdbc.Driver");
            StrategyConfig strategyConfig = new StrategyConfig();
            strategyConfig
                    .setCapitalMode(true)
                    .setEntityLombokModel(false)
                    .setDbColumnUnderline(true)
                    .setNaming(NamingStrategy.underline_to_camel)
    //              .setSuperMapperClass("cn.saytime.mapper.BaseMapper")
                    .setInclude(tableNames);//修改替换成你需要的表名,多个表名传数组
            config.setActiveRecord(false)
                    .setAuthor(author)
                    .setOutputDir("d:\codeGen")
                    .setFileOverride(true)
                    .setEnableCache(false);
            if (!serviceNameStartWithI) {
                config.setServiceName("%sService");
            }
            new AutoGenerator().setGlobalConfig(config)
                    .setDataSource(dataSourceConfig)
                    .setStrategy(strategyConfig)
                    .setPackageInfo(
                            new PackageConfig()
                                    .setParent(packageName)
                                    .setController("web")
                                    .setEntity("entity")
                                    .setMapper("dao")
                                    .setService("service")
                                    .setServiceImpl("service.impl")
                                    .setXml("mapper")
                    ).execute();
        }
    
    }

    4.测试

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import java.util.List;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class SpringbootMybatisPlusApplicationTests {
    
        @Autowired
        private SysUserService userService;
    
        @Test
        public void contextLoads() {
    
            // 所有用户
            List<SysUser> users = userService.selectList(null);
            System.out.println(users);
    
        }
    
    }

    5.启动文件添加注解

    @MapperScan(basePackages = "com.*.dao")
  • 相关阅读:
    Quartz.net官方开发指南 第十一课: 高级(企业级)属性
    .NET开源项目:Tomboy
    开源的作业调度框架 Quartz.NET
    DinnerNow.net: 微软最新技术集成示例
    将Quartz.NET集成到 Castle中
    评论:微软的SOA战略
    行为驱动开发Behaviour Driven Development
    Mono 1.2.5 发布,提供对IronPython和DLR的支持
    Quartz.net官方开发指南 第二课:Jobs And Triggers
    数据库厂商提供的 Providers for ASP.NET
  • 原文地址:https://www.cnblogs.com/paisen/p/10245621.html
Copyright © 2011-2022 走看看