SpringBoot integrates Mybatis to realize automatic code generation

MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all JDBC code and manual setting of parameters and obtaining result sets. MyBatis can use simple XML or annotations to configure and map native types, interfaces, and Java POJOs (Plain Old Java Objects) as records in the database.

I believe everyone is familiar with MyBatis. In actual development and application, there are many applications. It is often integrated with SpringBoot framework and Spring framework to develop related websites and services.

MyBatis has a powerful and practical function, that is, after being configured, it can help us generate code with one click and reduce the related development workload.

Now let's use MyBatis's code generator tool (mybatis-generator) to generate a set of codes for us. The generated code implements the CRUD function, and we can use it directly. The specific steps are as follows:

1. Create a SpringBoot project and create dao, domain, and mapper directories as follows:

Insert picture description here
2. Create database-related tables, omit the SQL statement here

3. Add pom.xml configuration dependency and modify the pom.xml file

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.20</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

Modify the build structure of the pom.xml file to complete the configuration of mybatis-generator, and replace it with the following configuration:

<build>
     <plugins>
       <plugin>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.7</version>
            <dependencies>
            <dependency>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-core</artifactId>
                <version>1.3.7</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.46</version>
            </dependency>
            </dependencies>
            <executions>
               <execution>
                    <id>mybnatis generator</id>
                    <phase>package</phase>
                    <goals>
                       <goal>generate</goal>
                    </goals>
                </execution>
             </executions>
             <configuration>
                 <!--允许移动生成的文件-->
                 <verbose>true</verbose>
                 <!--允许自动覆盖文件-->
                 <overwrite>false</overwrite>
                 <configurationFile>
                        src/main/resources/mybatis-generator.xml
                 </configurationFile>
             </configuration>
        </plugin>
    </plugins>
</build>

4. Configure the properties application.properties file as follows:

     server.port=8095
    mybatis.mapper-locations=classpath:mapping/*.xml
     
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/seckill?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    spring.datasource.username=root
    spring.datasource.password=root
    spring.datasource.name=seckill
    #使用druid数据源
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

5. Write the mybatis-generator.xml file, the content is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!--驱动包的路径-->
    <!--<classPathEntry location="C:\Users\lhf\.m2\repository\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar" />-->

    <!--数据库连接-->
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!--注释-->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
        </commentGenerator>
        <!--数据库连接地址及账号密码-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/seckill"
                        userId="root"
                        password="root">
        </jdbcConnection>

        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!--生成entity类存放位置-->
        <javaModelGenerator targetPackage="com.lhf.springboot.domain" targetProject="src/main/java">
            <!--是否对model添加构造函数-->
            <property name="constructorBased" value="false"/>
            <!--是否允许子包-->
            <property name="enableSubPackages" value="true"/>
            <!--建立的model对象是否不可变,也就是生成的model没有setter方法-->
            <property name="immutable" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="mapper"  targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!--生成Dao类的存放位置-->
        <!-- 客户端代码,生成易于使用的正对Model对象和XML配置文件的代码
        type="ANNOTATEDMAPPER", 生成Java Model和基于注解的Mapper对象
        type="MIXEDMAPPER", 生成基于注解的Java Model和相应的Mapper对象
        type="XMLMAPPER", 生成SQLMap XML文件和独立的Mapper接口
        -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.lhf.springboot.dao"  targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!--请根据自己数据库对应的表名进行配置修改,这里仅供参考-->
      <!--生成对应表及类名-->
       <table schema="mybatis" tableName="user_info" domainObjectName="User"
                enableInsert="true" enableSelectByExample="false"
                enableDeleteByPrimaryKey="false" enableDeleteByExample="false"
                enableCountByExample="false" enableUpdateByExample="false"
                enableSelectByPrimaryKey="true" enableUpdateByPrimaryKey="true"/>
        <table tableName="item" domainObjectName="Item" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false"
               enableInsert="true" enableDeleteByPrimaryKey="false" ></table>
        <table tableName="item_stock" domainObjectName="ItemStock" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false"
               enableInsert="true" enableDeleteByPrimaryKey="false" ></table>
        <table tableName="order_info" domainObjectName="OrderInfo" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false"
               enableInsert="true" enableDeleteByPrimaryKey="false" ></table>
    </context>

</generatorConfiguration>

6. Configure and execute the mybatis-generator file, configuration steps:

Run -> Edit Configurations -> + -> Maven -> Configuration, as shown in the figure:
Insert picture description here

7. Execute the generated code, Run -> Run'mybatis-generator', click Execute to generate the code, as shown in the figure:

Insert picture description here
8. Seeing the log is successful, the automatic code generation function is now complete! The generated code is shown in the figure:

Insert picture description here
Is it very simple? Please study the knowledge points related to SpringBoot and MyBatis integration.

Conclusion:

This is the end of the knowledge introduction. If you need to learn, you can click to enter . There are a lot of learning materials and interview materials for free.
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/m0_45270667/article/details/109402173