亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Mybatis官方生成器項目實戰入門教程

標簽:
Java 數據庫
概述

本文将详细介绍Mybatis官方生成器项目实战,包括环境搭建、代码生成、配置详解以及高级使用技巧等内容,帮助开发者快速上手Mybatis Generator。通过具体案例,我们将展示如何在实际项目中应用Mybatis Generator生成高效的MyBatis代码。

MyBatis官方生成器简介

MyBatis Generator是什么

MyBatis Generator (MBG) 是一个开源的代码生成工具,它是MyBatis的官方推荐工具。MBG旨在帮助开发人员自动生成MyBatis数据访问层的代码,包括Mapper接口、XML映射文件、实体类和配置文件等。这可以显著地减少开发人员编写和维护这些代码的工作量,从而提高开发效率。

为什么使用MyBatis Generator

在开发过程中,通常需要频繁地与数据库进行交互,而MyBatis的整个数据访问层代码需要手动编写,这不仅耗时,还容易出错。使用MyBatis Generator可以自动生成这些代码,实现自动化,从而节省时间并减少错误。此外,它还能保持与数据库表结构的一致性,自动维护代码的更新。

MyBatis Generator的基本概念和术语

  • GeneratorConfiguration: 配置文件的根元素,定义了生成器的基本配置。
  • context: 代表一个生成器上下文,通常可以定义多个context,每个context可以生成不同的代码。
  • table: 指定要生成代码的数据库表。
  • columnOverride: 用于覆盖表中列的默认生成行为。
  • property: 定义生成器的各种属性,如数据库驱动、数据库连接信息等。
  • tableElement: 指定特定表的配置,例如表名、主键列等。
  • modelType: 用于生成不同类型实体类的配置,如JavaBean、Map等。
MyBatis Generator环境搭建

开发环境准备

在开始使用MyBatis Generator之前,需要准备好开发环境。通常,环境包括以下几部分:

  • JDK 1.6及以上版本。
  • Maven或Gradle等构建工具。
  • MySQL或其他支持的数据库。
  • MyBatis框架及其依赖。
  • MyBatis Generator框架及其依赖。

下载并引入MyBatis Generator的依赖

可以通过Maven或Gradle等构建工具来下载并引入MyBatis Generator的依赖。这里以Maven为例进行说明:

在项目的pom.xml文件中添加以下依赖:

<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.4.0</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.26</version>
</dependency>

配置MyBatis Generator的配置文件

配置文件通常命名为generatorConfig.xml,该文件定义了生成器的配置信息,如数据库连接信息、表名、生成的代码类型等。以下是一个示例配置文件:

<generatorConfiguration>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <classPathEntry location="lib/mysql-connector-java-8.0.26.jar"/>
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/test"
            userId="root"
            password="password">
        </jdbcConnection>
        <javaModelGenerator targetPackage="com.example.model"
            targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <sqlMapGenerator targetPackage="com.example.mapper"
            targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper"
            targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <table tableName="user" domainObjectName="User" enableCountByExample="false"
            enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"/>
    </context>
</generatorConfiguration>
使用MyBatis Generator生成代码

生成基本的CRUD操作代码

生成器可以生成基本的CRUD操作代码。在generatorConfig.xml中配置相应的表信息,比如:

<table tableName="user" domainObjectName="User" enableCountByExample="false"
    enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
    selectByExampleQueryId="false"/>

生成的基本CRUD代码示例如下:

  • selectByPrimaryKey:查询主键。
  • insert:插入数据。
  • updateByPrimaryKey:更新主键记录。
  • deleteByPrimaryKey:删除主键记录。

生成自定义的Mapper接口和XML文件

可以通过配置文件自定义生成Mapper接口和对应的XML文件。例如,配置文件中添加以下内容:

<table tableName="user" domainObjectName="User" enableCountByExample="false"
    enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
    selectByExampleQueryId="false">
    <generatedKey column="id" sqlType="INTEGER" identity="true" />
</table>

生成的Mapper接口示例如下:

public interface UserMapper {
    int deleteByPrimaryKey(Integer id);
    int insert(User record);
    int insertSelective(User record);
    User selectByPrimaryKey(Integer id);
    int updateByPrimaryKeySelective(User record);
    int updateByPrimaryKey(User record);
}

生成的XML文件示例如下:

<mapper namespace="com.example.mapper.UserMapper">
    <resultMap id="BaseResultMap" type="com.example.model.User">
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="email" property="email" jdbcType="VARCHAR" />
    </resultMap>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer">
        select
        <if test="selectSelective">
            <if test="selectSelectiveColumns != null">
                ${selectSelectiveColumns}
            </if>
            <if test="selectSelectiveColumns == null">
                *
            </if>
        </if>
        <if test="selectSelective == null">
            *
        </if>
        from user
        where id = #{id,jdbcType=INTEGER}
    </select>
</mapper>

生成实体类和配置文件等其他相关代码

生成器可以生成实体类和相关的配置文件。例如,生成的实体类如下:

public class User {
    private Integer id;
    private String name;
    private String email;
    // Getters and Setters
}

生成的配置文件通常包括数据源配置、MyBatis配置等。例如,MyBatis配置文件示例如下:

<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/test" />
                <property name="username" value="root" />
                <property name="password" value="password" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/example/mapper/UserMapper.xml" />
    </mappers>
</configuration>
MyBatis Generator配置详解

配置文件的结构和各个标签的意义

生成器的配置文件通常由以下标签组成:

  • generatorConfiguration: 配置文件的根标签。
  • context: 生成器上下文配置,可以定义多个context。
  • commentGenerator: 生成注释的相关配置。
  • jdbcConnection: 数据库连接配置,包含数据库驱动、连接URL等信息。
  • javaModelGenerator: Java模型生成器配置,用于生成实体类。
  • sqlMapGenerator: SQL映射文件生成器配置,用于生成XML映射文件。
  • javaClientGenerator: Java客户端生成器配置,用于生成Mapper接口。
  • table: 数据库表配置,定义要生成代码的表信息。

常见的配置项及其作用

  • enableSubPackages: 是否生成子包。
  • targetPackage: 生成的代码包名。
  • targetProject: 生成的代码存放路径。
  • domainObjectName: 生成的实体类名。
  • enableCountByExample: 是否生成countByExample方法。
  • enableUpdateByExample: 是否生成updateByExample方法。
  • enableDeleteByExample: 是否生成deleteByExample方法。
  • enableSelectByExample: 是否生成selectByExample方法。
  • generatedKey: 自增长主键的配置信息。

如何根据项目需求自定义配置

可以根据项目需求自定义配置文件中的各个属性,例如:

  • 表名: 指定要生成代码的表名。
  • 实体类名: 自定义生成的实体类名。
  • 包名: 自定义生成的代码存放的包名。
  • 生成的文件路径: 自定义生成的文件存放路径。
  • 注释配置: 自定义生成的代码中的注释信息。
MyBatis Generator高级使用技巧

如何处理复杂的数据库表结构

对于复杂的数据库表结构,如多对多关系、继承关系等,可以通过自定义配置文件来处理。例如,配置文件中可以设置复杂的关联关系:

<table tableName="order" domainObjectName="Order" enableCountByExample="false"
    enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
    selectByExampleQueryId="false">
    <join tableName="product" joinColumn="productId" parentColumn="id">
        <property column="name" jdbcType="VARCHAR" />
    </join>
</table>

处理多对多关系和继承关系的代码生成

生成器可以通过配置文件来处理多对多关系和继承关系。例如,处理继承关系时,可以在父类和子类中配置:

<table tableName="employee" domainObjectName="Employee" enableCountByExample="false"
    enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
    selectByExampleQueryId="false">
    <generatedKey column="id" sqlType="INTEGER" identity="true" />
</table>
<table tableName="employee_parttime" domainObjectName="ParttimeEmployee" enableCountByExample="false"
    enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
    selectByExampleQueryId="false">
    <generatedKey column="id" sqlType="INTEGER" identity="true" />
    <extendsTable tableName="employee" />
</table>

使用MyBatis Generator生成动态SQL

MyBatis Generator可以生成动态SQL,例如:

<update id="updateByPrimaryKeySelective">
    update user
    <set>
        <if test="name != null">
            name = #{name,jdbcType=VARCHAR},
        </if>
        <if test="email != null">
            email = #{email,jdbcType=VARCHAR},
        </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
</update>

生成的动态SQL可以根据传入的参数动态构建SQL语句。

MyBatis Generator项目实战案例

实战项目需求分析

假设我们正在开发一个图书管理系统,需要实现图书的基本增删改查操作。数据库包含一张book表,包含idtitleauthorpublish_date等字段。

项目中MyBatis Generator的配置和使用

配置文件generatorConfig.xml示例如下:

<generatorConfiguration>
    <context id="BookTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <classPathEntry location="lib/mysql-connector-java-8.0.26.jar"/>
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3ibli/3306/library"
            userId="root"
            password="password">
        </jdbcConnection>
        <javaModelGenerator targetPackage="com.example.model"
            targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <sqlMapGenerator targetPackage="com.example.mapper"
            targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper"
            targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <table tableName="book" domainObjectName="Book" enableCountByExample="false"
            enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"/>
    </context>
</generatorConfiguration>

生成代码后的项目的整合和调试

生成代码后,需要在项目中整合并调试这些代码。例如,在src/main/java/com/example/mapper目录下生成了BookMapper.java和对应的BookMapper.xml文件。

BookMapper.java中,生成了以下方法:

public interface BookMapper {
    int deleteByPrimaryKey(Integer id);
    int insert(Book record);
    int insertSelective(Book record);
    Book selectByPrimaryKey(Integer id);
    int updateByPrimaryKeySelective(Book record);
    int updateByPrimaryKey(Book record);
}

BookMapper.xml中,生成了对应的SQL映射:

<mapper namespace="com.example.mapper.BookMapper">
    <resultMap id="BaseResultMap" type="com.example.model.Book">
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="title" property="title" jdbcType="VARCHAR" />
        <result column="author" property="author" jdbcType="VARCHAR" />
        <result column="publish_date" property="publishDate" jdbcType="DATE" />
    </resultMap>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer">
        select
        <if test="selectSelective">
            <if test="selectSelectiveColumns != null">
                ${selectSelectiveColumns}
            </if>
            <if test="selectSelectiveColumns == null">
                *
            </if>
        </if>
        <if test="selectSelective == null">
            *
        </if>
        from book
        where id = #{id,jdbcType=INTEGER}
    </select>
    <insert id="insert" parameterType="com.example.model.Book">
        insert into book (id, title, author, publish_date)
        values (#{id,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{author,jdbcType=VARCHAR}, #{publishDate,jdbcType=DATE})
    </insert>
</mapper>

src/main/resources目录下,生成了mybatis-config.xml配置文件:

<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/library" />
                <property name="username" value="root" />
                <property name="password" value="password" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/example/mapper/BookMapper.xml" />
    </mappers>
</configuration>

在项目中使用生成的Mapper接口:

public class BookService {
    private BookMapper bookMapper;

    public void addBook(Book book) {
        bookMapper.insert(book);
    }

    public Book getBookById(Integer id) {
        return bookMapper.selectByPrimaryKey(id);
    }

    public void updateBook(Book book) {
        bookMapper.updateByPrimaryKey(book);
    }

    public void deleteBook(Integer id) {
        bookMapper.deleteByPrimaryKey(id);
    }
}
點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消