Hibernate根据写好的pojo启动服务器会自动帮助我们生成对应的数据表。
MBG根据表帮我们自动生成接口、pojo类和xml这些文件。一般根据MyBatis GeneratorXML配置文件设置生成简单的CRUD,有关关联的操作推荐我们自己添加。
mybatis工具github网址:https://github.com/mybatis
MyBatis Generator(MBG)官方文档:http://www.mybatis.org/generator/
新建一个maven web项目
1、pom.xml引出 mybatis-generator 依赖
<!-- mybatis-generator -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
2、新建MyBatis GeneratorXML配置文件:自定义文件名 mbgconfig.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>
<!--targetRuntime用MyBatis3, 也就是默认的-->
<context id="mysqlTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 去除自动生成的注释 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--基础的数据库连接-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis_demo?allowMultiQueries=true"
userId="root"
password="123456">
</jdbcConnection>
<!--Java类型解析器, 目前也就只有forceBigDecimals-->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- Domain生成器,即java实体类 -->
<javaModelGenerator targetPackage="cn.jq.mybatis.model" targetProject=".\src\main\java">
<!--据说可以自动添加schema名-->
<property name="enableSubPackages" value="true"/>
<!--当遇到String的时候setter是否会先trim()-->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--Mapping生成器,即生成的 Mapper.xml 文件位置-->
<sqlMapGenerator targetPackage="cn.jq.mybatis.dao" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!--Mapper生成器, 即生成的 Mapper 接口类,当type为ANNOTATEDMAPPER时是带有@annotation的Mapper, MIXEDMAPPER是XML文件-->
<javaClientGenerator type="XMLMAPPER" targetPackage="cn.jq.mybatis.dao" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!--字段命名策略过程: table标签对应数据库中的table表-->
<table tableName="t_user" domainObjectName="User"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
<table tableName="t_role" domainObjectName="Role"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
3、测试运行生成接口、pojo类和xml这些文件
参考官方文档:http://www.mybatis.org/generator/running/runningWithJava.html
@Test
public void runmbg() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
String path = this.getClass().getClassLoader().getResource("mbgconfig.xml").getPath();
File configFile = new File(path);
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
生成简单的CRUDmpper的接口(复杂的方法推荐自己写),生成的mapper.xml 书写很规范,多多参考规范。
一个较为完整的mbgconfig.xml示例, 保存下来按需修改
配置文件详解参考文章:https://blog.csdn.net/s0009527/article/details/78083763
<?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>
<!-- 数据库的驱动, JAR/ZIP文件的全路径,maven工程,驱动已经依赖了,没用-->
<classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip"/>
<!--targetRuntime用MyBatis3, 也就是默认的-->
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 去除自动生成的注释 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--基础的数据库连接-->
<jdbcConnection driverClass="COM.ibm.db2.jdbc.app.DB2Driver"
connectionURL="jdbc:db2:TEST"
userId="db2admin"
password="db2admin">
</jdbcConnection>
<!--Java类型解析器, 目前也就只有forceBigDecimals-->
<javaTypeResolver>
<!--当数据类型为DECIMAL或者NUMERIC的时候, 如果是true的话则总是使用java.math.BigDecimal-->
<!--以下是false, 即默认值的情况-->
<!--如果有小数或者decimal长度大于18, Java类型为BigDecimal-->
<!--如果没有小数, 以及decimal长度为10至18, Java类型为Long-->
<!--如果没有小数, 以及decimal长度为5至9, Java类型为Integer-->
<!--如果没有小数, 以及decimal长度少于5, Java类型为Short-->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!--Domain生成器-->
<javaModelGenerator targetPackage="test.model" targetProject=".\src\main\java">
<!--据说可以自动添加schema名, 可是我没用到过-->
<property name="enableSubPackages" value="true"/>
<!--生成全属性构造器, 没什么用, 如果有指定immutable元素的话这个会被忽略-->
<property name="constructorBased" value="true"/>
<!--生成不可变的domain, 这个我也很少用-->
<property name="immutable" value="true"/>
<!--每个Domain都继承这个bean-->
<property name="rootClass" value="com.github.prontera.domain.base.BasicEntity"/>
<!--当遇到String的时候setter是否会先trim()-->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--Mapping生成器-->
<sqlMapGenerator targetPackage="test.xml" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!--Mapper生成器, 当type为ANNOTATEDMAPPER时是带有@annotation的Mapper, MIXEDMAPPER是XML文件-->
<javaClientGenerator type="XMLMAPPER" targetPackage="test.dao" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
<!--每个Mapper所继承的接口-->
<property name="rootInterface" value="com.github.prontera.Mapper"/>
</javaClientGenerator>
<!--字段命名策略过程: <columnRenamingRule> >> property name="useActualColumnNames"-->
<!--alias属性是个神器, 会为所有SQL都添加, 做关联的时候就非常方便了-->
<!--至于什么Example, 全关了就是-->
<table alias="ha" tableName="ALLTYPES" domainObjectName="Customer"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
<!--指定是否用数据库中真实的字段名, 而不是采用MBG转换后的驼峰-->
<property name="useActualColumnNames" value="true"/>
<!--自动集成改类-->
<property name="rootClass" value="com.github.prontera.domain.base.HelloBasicClass"/>
<!--Mapper自动继承的接口-->
<property name="rootInterface" value="com.github.prontera.Mapper"/>
<!--当遇到String的时候setter是否会先trim()-->
<property name="trimStrings" value="true"/>
<!--先进行columnRenamingRule, 再进行useActualColumnNames. 如果有columnOverride则忽略该配置-->
<!--关于columnRenamingRule的具体例子 http://www.mybatis.org/generator/configreference/columnRenamingRule.html-->
<columnRenamingRule searchString="^CUST_" replaceString=""/>
<!--顾名思义, 忽略某些列-->
<ignoreColumn column="CREATE_TIME"/>
<!--也是忽略数据列, 但是可以通过正则表达式, except子元素是可选的, 代表忽略除UPDATE_TIME外的列-->
<ignoreColumnsByRegex pattern=".*_TIME$">
<except column="UPDATE_TIME"/>
</ignoreColumnsByRegex>
</table>
</context>
</generatorConfiguration>