美文网首页
SpringBoot整合Mybatis自动生成代码

SpringBoot整合Mybatis自动生成代码

作者: 小玉1991 | 来源:发表于2021-06-07 15:55 被阅读0次

1、新建SpringBoot项目,引入依赖包

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>
        
        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>

        <!--代码自动生成插件-->
        <!--使用完必须注释掉下面这个插件-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.6</version>
        </dependency>

2、编写generatorConfig.xml并配置到build中

<!DOCTYPE generatorConfiguration PUBLIC
        "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <context id="mysql" targetRuntime="MyBatis3">

        <!-- 数据Model属性对应Column获取插件 -->
        <plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
        <!-- 批量插入插件 -->
        <plugin type="com.itfsw.mybatis.generator.plugins.BatchInsertPlugin"/>

        <!-- 数据Model链式构建插件 -->
        <plugin type="com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin"/>

        <!-- 查询单条数据插件 -->
        <plugin type="com.itfsw.mybatis.generator.plugins.SelectOneByExamplePlugin"/>

        <!-- 查询结果选择性返回插件 -->
        <plugin type="com.itfsw.mybatis.generator.plugins.SelectSelectivePlugin" />

        <!-- MySQL分页插件 -->
        <plugin type="com.itfsw.mybatis.generator.plugins.LimitPlugin"/>

        <!-- Example 目标包修改插件 -->
        <plugin type="com.itfsw.mybatis.generator.plugins.ExampleTargetPlugin">
            <!-- 修改Example类生成到目标包下 -->
            <property name="targetPackage" value="com.songguo.ai.feixong.provider.mybatis.example"/>
        </plugin>
        <plugin type="com.itfsw.mybatis.generator.plugins.TableRenamePlugin" />


        <commentGenerator>
            <property name="suppressDate" value="true"/>
        </commentGenerator>


        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://10.xxx.xxx.120:6033/xxx"
                        userId="xxxx"   password="Abcd@xxxxx">
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成vo对象 -->
        <javaModelGenerator targetPackage="com.songguo.ai.feixong.provider.mybatis.domain" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaModelGenerator>

        <!-- 生成DAO的类文件以及配置文件 -->
        <sqlMapGenerator targetPackage="com.songguo.ai.feixong.provider.mybatis.mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- 生成mapper类 -->
        <javaClientGenerator targetPackage="com.songguo.ai.feixong.provider.mybatis.mapper" targetProject="src/main/java" type="XMLMAPPER">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

       
<!--配置上下边代码后,就可以获得insert之后的数据的id。
      会生成:
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      SELECT LAST_INSERT_ID()
    </selectKey>
        等同于:useGeneratedKeys="true" keyProperty="id"
identity=true,是AFTER
identify=false(默认),是BEFORE。如果你的数据表设置的id是自增长的,在插入前数据就有了id,会报错: Duplicate entry '7' for key 'PRIMARY'
-->
       <table tableName="city_group" >
            <generatedKey column="id"  sqlStatement="SELECT LAST_INSERT_ID()" identity="true"/>
        </table>
<!--        <table tableName="city_auth" />-->
<!--        <table tableName="city_group" />-->
<!--        <table tableName="city_group_mapping" />-->
<!--        <table tableName="city_group_model_group_mapping" />-->
<!--        <table tableName="city_group_model_group_mapping_expand" />-->
<!--        <table tableName="model" />-->
<!--        <table tableName="model_group" />-->
<!--        <table tableName="model_group_expand" />-->
<!--        <table tableName="operation" />-->

    </context>
</generatorConfiguration>
<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-archetype-plugin</artifactId>
                <version>3.0.1</version>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.3</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>prepare-agent</goal>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <!--MyBatis自动生成代码的插件和配置-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.6</version>
                <configuration>
                    <!-- 在控制台打印执行日志 -->
                    <verbose>true</verbose>
                    <!-- 重复生成时会覆盖之前的文件-->
                    <overwrite>true</overwrite>
                    <configurationFile>src/main/resources/mybatis/generatorConfig.xml</configurationFile>
                </configuration>
                <!-- 数据库连接选择8.0以上的,因为用的mysql8.0-->
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.6</version>
                    </dependency>
                    <dependency>
                        <groupId>org.mybatis</groupId>
                        <artifactId>mybatis-spring</artifactId>
                        <version>1.3.2</version>
                    </dependency>
                    <dependency>
                        <groupId>com.itfsw</groupId>
                        <artifactId>mybatis-generator-plugin</artifactId>
                        <version>${mybatis.generator.plugin.version}</version>
                    </dependency>
                </dependencies>
            </plugin>

        </plugins>
    </build>
generatorConfig.xml文件所在位置

3、配置数据源,这里用DynamicDataSource多数据源的方案配置

@Aspect
@Component
@Slf4j
public class DataSourceAOP {

    @Before("execution(* com.songguo.ai.feixong.provider.mybatis.*.*(..))")
    public void setGeoDataSourceType(JoinPoint point) {
        DynamicDataSource.setFeixiong();
    }
}
=====================================
@Configuration
public class DataSourceConf {


    public DataSourceConf() {
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.feixiong")
    public DataSource feixiong() {
        return new DruidDataSource();
    }

    @Autowired
    @Primary
    @Bean("dataSource")
    public DynamicDataSource dynamicDataSource(@Qualifier("feixiong") DataSource feixiong) {
        Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
        targetDataSources.put(DynamicDataSource.DatabaseType.FEI_XIONG, feixiong);

        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法
        dataSource.setDefaultTargetDataSource(feixiong);
        return dataSource;
    }
}
========================================
@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {
    private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<DatabaseType>();

    @Override
    protected Object determineCurrentLookupKey() {
        return contextHolder.get();
    }

    public static void setFeixiong() {
        contextHolder.set(DatabaseType.FEI_XIONG);
    }

    public static void setMozi() {
        contextHolder.set(DatabaseType.MOZI);
    }


    public static DatabaseType getType() {
        return contextHolder.get();
    }


    public static enum DatabaseType {
        FEI_XIONG, MOZI
    }
}

application-dev.properties

#db
spring.datasource.feixiong.url=jdbc:mysql://10.100.67.120:6033/feixiong?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&connectTimeout=2000&socketTimeout=2000&zeroDateTimeBehavior=convertToNull
spring.datasource.feixiong.username=geo_usertest
spring.datasource.feixiong.password=Abcd@123
spring.datasource.feixiong.initial-size=5
spring.datasource.feixiong.max-active=20
spring.datasource.feixiong.min-idle=5
spring.datasource.feixiong.max-wait=2000
spring.datasource.feixiong.stat-view-servlet.login-username=admin
spring.datasource.feixiong.stat-view-servlet.login-password=admin

mybatis.mapper-locations=classpath:mapper/**/*.xml

bootstrap.yml

spring:
  profiles:
    active: dev
  application:
    name: xxxxx

server:
  servlet:
    context-path: /${spring.application.name}
  port: 8080

---
spring:
  profiles: dev
  cloud:
    nacos:
      config:
        server-addr: 10.xxxx.xxx.20:8848
        file-extension: yml
        namespace: xxxxxxxxxxxx-c0930c1ec810
        username: xxxxdev_nacos
        password: 4xxxxxFU9
      discovery:
        server-addr: 10.xxxx.xxx.20:8848
        file-extension: yml
        namespace: xxxxxxxxxxxx-c0930c1ec810
        username: xxxxdev_nacos
        password: 4xxxxxFU9

Application.java

@SpringBootApplication(scanBasePackages = {"com.xxxx.*"}, exclude = {DataSourceAutoConfiguration.class})
@MapperScan({"com.xxxx.**.mapper", "com.xxxx.**.mapper"})
public class  Application {

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

}

自动生成mybatis代码的操作


编辑好后,直接选择然后运行

.

注意:要确保src.main下有java和resources目录,才能成代码


image.png

简单使用:

        CityGroupExample cityGroupExample = new CityGroupExample();
        CityGroupExample.Criteria criteria = cityGroupExample.createCriteria();
        criteria.andIsValidEqualTo((byte) 1);
       
 //设置分页,row为每页的数量,offset是从第几条数据开始(忽略掉的数据条数)
        cityGroupExample.setRows(4);
        cityGroupExample.setOffset(1);
        cityGroupExample.setOrderByClause("id DESC");

        List<CityGroup> cityGroups = cityGroupMapper.selectByExample(cityGroupExample);

相关文章

网友评论

      本文标题:SpringBoot整合Mybatis自动生成代码

      本文链接:https://www.haomeiwen.com/subject/quvzgktx.html