用mybatis-generator自动生成实体类、dao、mapping.xml文件(eclipse插件)

mybatis-generator有三种用法:命令行、eclipse插件、maven插件。

1.在eclipse的market中搜索mybatis generator插件,安装

用mybatis-generator自动生成实体类、dao、mapping.xml文件(eclipse插件)

New--other--中出现下面的内容则是安装成功

用mybatis-generator自动生成实体类、dao、mapping.xml文件(eclipse插件)

2.新建一个web工程

用mybatis-generator自动生成实体类、dao、mapping.xml文件(eclipse插件) 

导入依赖的jar包,其中mybatis-generator-core-1.3.2.jar是自动生成的核心包。

附上mybatis-generator的jar包和英文说明文档下载链接:

链接:https://pan.baidu.com/s/19qCfyYyIP_I9UZ73HR3kOg 
提取码:wmi5

3.New--other去创建generatorConfig.xml配置文件

用mybatis-generator自动生成实体类、dao、mapping.xml文件(eclipse插件)

<?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 id="context1" defaultModelType="flat">
    <commentGenerator>  
        <!-- 是否去除自动生成的注释 true:是 : false:否 -->
        <property name="suppressAllComments" value="true" />  
    </commentGenerator>  

     <!-- 数据库连接的信息:驱动类、连接地址、用户名、密码-->
    <jdbcConnection connectionURL="jdbc:mysql://127.0.0.1:3306/billing_system2?characterEncoding=utf8" driverClass="com.mysql.jdbc.Driver" password="123456" userId="root" />
    <!-- targetProject:生成PO类的位置-->
    <javaModelGenerator targetPackage="com.jwzt.charge.model" targetProject="mybatisgenerator/src" />
	<!-- targetProject:mapper映射文件生成的位置  -->
    <sqlMapGenerator targetPackage="com.jwzt.charge.sql" targetProject="mybatisgenerator/src" />
	<!-- targetPackage:mapper接口生成的位置  -->
    <javaClientGenerator targetPackage="com.jwzt.charge.dao" targetProject="mybatisgenerator/src" type="XMLMAPPER" />
    <table tableName="custbean">
        <!-- 放开下面的代码,不会生成example实体类 -->
		<!-- enableCountByExample="false" -->
		<!-- enableUpdateByExample="false" -->
		<!-- enableDeleteByExample="false" -->
		<!-- enableSelectByExample="false" -->
		<!-- selectByExampleQueryId="false"> -->
    </table>
    
  </context>
</generatorConfiguration>

4.右键运行选择“run mybatis generator”

用mybatis-generator自动生成实体类、dao、mapping.xml文件(eclipse插件)

自动生成的实体类、dao、mapping.xml文件

用mybatis-generator自动生成实体类、dao、mapping.xml文件(eclipse插件)

生成的实体类中会多出来一个Example的实体类,Example类包含一个内部静态类 Criteria,利用Criteria我们可以在类中根据自己的需求动态生成sql where字句,不用我们自己再修改mapper文件添加或者修改sql语句了,能节省很多写sql的时间。 

例如:

CustbeanExample ex = new CustbeanExample();
ex.createCriteria().andCustnameLike("小明");
List<Custbean> custlist  = custdao.selectByExample(ex);

不生成Example实体类,把配置文件中的table修改为下面的这样即可:

 <table tableName="custbean"
		enableCountByExample="false"
		enableUpdateByExample="false"
		enableDeleteByExample="false"
		enableSelectByExample="false"
		selectByExampleQueryId="false">
 </table>

建议新建一个新的项目,创建和原来项目一样的package路径,生成文件后拷贝到原来的项目,直接在原项目生成文件可能会覆盖掉之前的文件,所以新建拷贝的方式比较安全,拷贝又不会很麻烦。