MybatisGenerator 教程

本文详细介绍使用MyBatisGenerator自动生成MyBatis代码的过程,包括配置Maven依赖、编写generatorContext.xml配置文件、运行MyBatisGenerator以及测试生成代码的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用MybatisGenerator自动生成Mybatis代码

使用mybatis虽然方便,但是每个表都要写一个实体类,一个dao文件和一个xml文件,命名它们结构这么相似,虽然我们能写,但是我们程序员都是懒惰的,能够用代码自动写的就没必要用手写啦,但是新手学习还是要脚踏实地,亲手写出来才能对mybatis更加了解
不过不要担心,我们所担心的东西,早就有前辈们帮我们担心过了,早就有前辈帮我们把工具写出来了,只需要我们去使用就行了,让我们去官网看看mybatisGenerator官网,我们只需要配置generatorContext.xml配置文件即可,配置文件标签详情可见官网配置文件标签介绍

1、添加Maven

<!--数据源连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

        <!--mysql jdbc连接-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--junit 单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!--spring 提供的测试环境-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring bean管理,实现依赖注入和控制反转-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring mybatis集成包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!--spring jdbc 集成包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring-context 注解扫描等功能需要-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- mybatis 包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.0</version>
        </dependency>

        <!--mybatisGenerator jar包-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>

2、编写generatorContext.xml文件

我这里只写了一份简单的配置文件文件模板,有其他需要的可以在官网中查看标签的介绍,根据需要自行添加标签官网配置文件标签介绍

<?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>

	<!--
		context标签中targetRuntime属性是生成Mapper接口和xml文件需要自动生成的方法类型,有多种,在这里介绍两种
		Mybatis3:生成的方法
			long countByExample(UserExample example);

		    int deleteByExample(UserExample example);
		
		    int deleteByPrimaryKey(Long id);
		
		    int insert(User record);
		
		    int insertSelective(User record);
		
		    List<User> selectByExample(UserExample example);
		
		    User selectByPrimaryKey(Long id);
		
		    int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);
		
		    int updateByExample(@Param("record") User record, @Param("example") UserExample example);
		
		    int updateByPrimaryKeySelective(User record);
		
		    int updateByPrimaryKey(User record);
			
		Mybatis3Simple:默认生成的方法
			int deleteByPrimaryKey(Long id);

		    int insert(User record);
		
		    User selectByPrimaryKey(Long id);
		
		    List<User> selectAll();
		
		    int updateByPrimaryKey(User record);
	  
	  可以根据需要自行选择
	-->
    <context id="Mysql" defaultModelType="flat" targetRuntime="MyBatis3Simple">
        <!--自动设置分隔符-->
        <property name="autoDelimitKeywords" value="true"/>
        <!-- 设置分隔符 -->
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

		<!--添加官方提供插件,为每个实体类实现Serializable接口-->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>

        <!--设置要使用java文件的字符编码-->
        <!--<property name="javaFileEncoding" value="UTF-8"/>-->

        <!--注释生成标签-->
        <commentGenerator>
            <!--阻止生成注释,默认为false-->
            <property name="suppressAllComments" value="false"/>
            <!--阻止生成的注释包含时间戳,默认为false-->
            <property name="suppressDate" value="false"/>
            <!--自定义注释中时间显示的格式-->
            <property name="dateFormat" value="yyyy-MM-dd"/>
            <!--注释是否添加表的备注信息,默认为false-->
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>

        <!--jdbc连接-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/test"
                        userId="root"
                        password="abcdef"
                        >
        </jdbcConnection>

        <!--配置jdbc类型和java类型如何转化-->
        <!--forceBigDecimals属性可以控制是否强制将 DECIMAL 和 NUMERIC 类型的 JDBC 字段转换为 Java 类型的-->
        <!--java.math . BigDecimal ,默认值为 false,一般不需要配置-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!--控制生成的实体类-->
        <!--targetPackage 生成实体类存放的包名
        targetProject 生成实体类的项目路径-->
        <javaModelGenerator targetPackage="javaDIYFree.model" targetProject="src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
		<!--targetPackage 生成mapper.xml文件的文件夹名称
		targetProject 所在资源路径-->
        <sqlMapGenerator targetPackage="mapper"  targetProject="src\main\resources">
        	<!--是否生成子包-->
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
		<!--
			生成dao层的标签,
			type属性:XMLMAPPER	生成的对象将是MyBatis 3.x映射器基础结构的Java接口。接口将依赖于生成的XML映射器文件
			targetPackage:生成文件所在的包
		-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="javaDIYFree.dao"  targetProject="src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        
		<!--
			需要自动生成的表
			tableName:表名
			domainObjectName:生成的实体类名称,默认根据表明自动生成
			enableCountByExample:是否生成该方法,后面的都类似
		-->
        <table  tableName="user" domainObjectName="User"  enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false" selectByExampleQueryId="false">
        </table>

    </context>
</generatorConfiguration>

运行MybatisGenerator

运行MybatisGenerator,有多种方法,可以通过maven插件方式运行,也可以通过main方法运行,如果不需要扩展的话可以直接通过maven插件运行,如果需要扩展的话建议通过java main方法运行,可进官网查看运行MybatisGenerator

maven plugin

		<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.5</version>
				<dependencies>
					<dependency>
						<groupId> mysql</groupId>
						<artifactId> mysql-connector-java</artifactId>
						<version> 5.1.39</version>
					</dependency>
					<dependency>
						<groupId>org.mybatis.generator</groupId>
						<artifactId>mybatis-generator-core</artifactId>
						<version>1.3.5</version>
					</dependency>
				</dependencies>
				<executions>
					<execution>
						<id>Generate MyBatis Artifacts</id>
						<phase>package</phase>
						<goals>
							<goal>generate</goal>
						</goals>
					</execution>
				</executions>
				<configuration>
					<!--允许移动生成的文件 -->
					<verbose>true</verbose>
					<!-- 是否覆盖 -->
					<overwrite>true</overwrite>
					<!-- 自动生成的配置 -->
					<configurationFile>
						src/main/resources/mybatis-generator.xml</configurationFile>
				</configuration>
			</plugin>

java main方式运行


import org.junit.Test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Hearts
 * @date 2019/4/18
 * @desc
 */
public class MybatisGeneratorPluginTest {

    public static void main(String[] args) {
        try {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            //获得配置文件流
            InputStream is = classloader.getResourceAsStream("mybatis-generator.xml");
            //创建一个配置文件解析器
            ConfigurationParser cp = new ConfigurationParser(warnings);
            //将配置文件解析成Configuration对象
            Configuration config = cp.parseConfiguration(is);
            //设置文件处理,是否覆盖
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            //创建MybatisGenerator对象
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            //执行生成代码程序
            myBatisGenerator.generate(null);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (InvalidConfigurationException e) {
            e.printStackTrace();
        } catch (XMLParserException e) {
            e.printStackTrace();
        }
    }

测试生成的代码

package javaDIYFree.dao;

import javaDIYFree.config.MybatisConfig;
import javaDIYFree.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.function.Consumer;

/**
 * @author Hearts
 * @date 2019/4/17
 * @desc
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MybatisConfig.class)
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    /**
     * 测试insert方法
     */
    public void insertUser(){
        User user = new User();
        user.setUsername("zhangsan");
        user.setPassword("123456");
        userMapper.insert(user);
    }

    @Test
    /**
     * 测试selectAll方法
     */
    public void selectAllUser(){

        userMapper.selectAll().forEach(new Consumer<User>() {
            public void accept(User i) {
                //打印用户名和密码
                System.out.println(i.getUsername() +" ======> "+i.getPassword());
            }
        });
    }
}

项目结构图

项目结构图

结束

有什么意见,欢迎大家一起讨论!!如果需要查看环境配置的可去上一篇文章mybatis+spring环境配置

mybatis也能方向生成代码,能方向生成实体类(po)、mapper接口和Mapper接口映射文件,能减少我们代码的工作量。详细步骤如下 1、下载mybatis生成架包工具MyBatis_Generator_1.3.1.zip,解压架包把features、plugins文件夹下的架包分别拷贝到eclipse安装目录下的features、plugins文件夹。重启eclipse就行。 解压后图片如下: Eclipse路径如图: 拷贝替换如图: 2、创建generatorConfig.xml文件,安装好mybatis 就能创建generatorConfig.xml 3、配置generatorConfig.xml配置文件,详细如下 [html] view plain copy <?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="D:\\rep\\mysql\\mysql-connector-java\\5.1.19\\mysql-connector-java-5.1.19.jar" /> --> <classPathEntry location="D:\\repo\\com\\oracle\\ojdbc14\\10.2.0.1.0\\ojdbc14-10.2.0.1.0.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressAllComments" value="true" /> <property name="suppressDate" value="true" /> </commentGenerator> <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@xxx.xxx.xxx.xxx:1521:orcl4" userId="xxx" password="xxxx" /> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --> </javaTypeResolver> <javaModelGenerator targetPackage="com.pcmall.domain.sale.order" targetProject="pos-service/src/main/java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <sqlMapGenerator targetPackage="mybatis.mapper.sale.order" targetProject="pos-service/src/main/resources"> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <javaClientGenerator targetPackage="com.pcmall.dao.sale.order" targetProject="pos-service/src/main/java" type="XMLMAPPER"> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <table tableName="hs_zxzflx" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false" selectByExampleQueryId="true" enableUpdateByExample="false"> <!-- <generatedKey column="ID" sqlStatement="oracle" identity="true" /> --> </table> </context> </generatorConfiguration> 4、右击generatorConfig.xml 点击Generate MyBatis/iBATIS Artifacts 生成对应接口、接口映射文件、实体类 5、查看结果
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值