溫馨提示×

mybatis generator自動生成代碼怎么配置

小億
134
2023-12-28 10:40:30
欄目: 編程語言

要配置MyBatis Generator自動生成代碼,需要進(jìn)行以下步驟:

1. 添加MyBatis Generator插件依賴:在項目的`pom.xml`文件中添加MyBatis Generator插件的依賴。例如:

<build>

  <plugins>

    <!-- MyBatis Generator插件 -->

    <plugin>

      <groupId>org.mybatis.generator</groupId>

      <artifactId>mybatis-generator-maven-plugin</artifactId>

      <version>1.4.0</version>

      <dependencies>

        <!-- 選擇合適的MySQL驅(qū)動程序 -->

        <dependency>

          <groupId>mysql</groupId>

          <artifactId>mysql-connector-java</artifactId>

          <version>8.0.23</version>

        </dependency>

        <!-- 其他數(shù)據(jù)庫驅(qū)動程序依賴 -->

      </dependencies>

      <executions>

        <execution>

          <id>Generate MyBatis Artifacts</id>

          <phase>generate-sources</phase>

          <goals>

            <goal>generate</goal>

          </goals>

        </execution>

      </executions>

      <configuration>

        <!-- 配置MyBatis Generator的生成規(guī)則 -->

      </configuration>

    </plugin>

  </plugins>

</build>

請確保將`<groupId>`、`<artifactId>`和`<version>`設(shè)置為正確的值,并根據(jù)你使用的數(shù)據(jù)庫選擇相應(yīng)的驅(qū)動程序依賴。

2. 配置MyBatis Generator生成規(guī)則:在插件的`<configuration>`標(biāo)簽中,可以配置MyBatis Generator的生成規(guī)則。

例如:

配置數(shù)據(jù)庫連接信息:

<jdbcConnection>

  <driverClass>com.mysql.cj.jdbc.Driver</driverClass>

  <connectionURL>jdbc:mysql://localhost:3306/mydatabase</connectionURL>

  <userId>root</userId>

  <password>password</password>

</jdbcConnection>

根據(jù)你的數(shù)據(jù)庫類型和連接信息修改`<driverClass>`、`<connectionURL>`、`<userId>`和`<password>`。

配置生成實體類:

<table tableName="mytable" domainObjectName="MyTableEntity">

  <generatedKey column="id" sqlStatement="JDBC" identity="true" />

</table>

將`<tableName>`設(shè)置為需要生成實體類的表名,將`<domainObjectName>`設(shè)置為生成的實體類名。如果有主鍵自增

列,可以使用`<generatedKey>`配置生成主鍵策略。

配置生成Mapper接口和XML文件:

<table tableName="mytable" domainObjectName="MyTableEntity" mapperName="MyTableMapper">

  <generatedKey column="id" sqlStatement="JDBC" identity="true" />

</table>

將`<tableName>`設(shè)置為需要生成Mapper接口和XML文件的表名,將`<domainObjectName>`設(shè)置為對應(yīng)的實體類名,

將`<mapperName>`設(shè)置為生成的Mapper接口名。

3. 運(yùn)行生成命令:在項目根目錄下打開終端或命令行窗口,執(zhí)行以下命令來啟動代碼生成器:

mvn mybatis-generator:generate

執(zhí)行成功后,MyBatis Generator將根據(jù)配置生成相應(yīng)的代碼文件。

0