MyBatis使用Generator自动生成代码

系统 1712 0

MyBatis中,可以使用Generator自动生成代码,包括DAO层、 MODEL层 、MAPPING SQL映射文件。

第一步:
配置好自动生成代码所需的XML配置文件,例如(generator.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>
<!-- classPathEntry:数据库的JDBC驱动-->
  <classPathEntry location="F:\Jansun\workspace\wicketAjax\ojdbc14-10.2.0.1.jar" />
 
  <context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 去除自动生成的注释 -->
<commentGenerator>
 <property name="suppressAllComments" value="true" />
</commentGenerator>
 
    <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
        connectionURL="jdbc:oracle:thin:@10.87.61.233:1521:orcl11g"
        userId="ibis"
        password="ibis">
    </jdbcConnection>
 
    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>
 
<!-- targetProject:自动生成代码的位置 -->
    <javaModelGenerator targetPackage="com.test.model" targetProject="F:\Jansun\workspace\wicketAjax\src">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>
 
    <sqlMapGenerator targetPackage="com.test.mapping"  targetProject="F:\Jansun\workspace\wicketAjax\src">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>
 
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.test.dao"  targetProject="F:\Jansun\workspace\wicketAjax\src">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>
 
<!-- tableName:用于自动生成代码的数据库表;domainObjectName:对应于数据库表的javaBean类名 -->
    <table schema="ibis" tableName="ibis_info" domainObjectName="Ibis" >
      
    </table>
 
  </context>
  
</generatorConfiguration>
 
第二步:下载 mybatis-generator-core-1.3.1.jar 包。
 
第三步:进入XML配置文件(generator.xml)所在的的目录并执行命令:
 
java -jar F:\mybatis-generator-core-1.3.1\lib\mybatis-generator-core-1.3.1.jar -configfile genrator.xml -overwrite
 
(PS:F:\mybatis-generator-core-1.3.1\lib\mybatis-generator-core-1.3.1.jar,是你所下载的 mybatis-generator-core-1.3.1.jar包所在的目录
//--------------------------------------------------------------------------------------
 

Mybatis-generator-------------Mybatis 的代码生成器

使用 Hibernate 可以很方便的生成 model,dao, 和映射配置文件 . mybatis 也有生成器 , mybatis generator,  简称 MBG.  下面为大家介绍一下 MBG 的使用 .

 

    Mybatis-generator 的思想是编写一个配置文件,然后运行该配置文件,就会得到相应的 java 代码。那么重点就是这个配置文件,配置文件中都需要些什么呢?必须包括的有数据库的 datasource Mybatis 的版本信息,至少一个的数据表,还有是需要生成的代码所在的包的信息。

 

1. 下载类包

下载 mybatis-generator-core-1.3.1-bundle.zip 之后 解压得到 mybatis-generator-core-1.3.1.jar,  即生成器的 jar mybatis-3.0.6.jar mybatis-generator-core-1.3.1.jar 加入到项目的 lib 然后编写一个生成器的配置文件 generatorConfig.xml.

2. mybatis-generator 的配置文件

mybatis-generator 最重要的就是一个配置文件,配置文件中配置了生成的 .dao  pojo 生成的 package 路径等。

介绍一下 genernatorConfig.xml

    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<? xml version = "1.0" encoding = "UTF-8" ?>
<!DOCTYPE generatorConfiguration 
 
   PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 
 
 
    
 
< generatorConfiguration
 
     < properties resource = "com/yuan/mybatis/mbg/util/generatorConfig.properties" /> 
 
     < classPathEntry location = "${classPath}" /> 
 
     < context id = "MBG" targetRuntime = "MyBatis3" defaultModelType = "conditional"
 
         < plugin type = "org.mybatis.generator.plugins.EqualsHashCodePlugin" /> 
 
         < plugin type = "org.mybatis.generator.plugins.MapperConfigPlugin"
 
             < property name = "fileName" value = "GeneratedMapperConfig.xml" /> 
 
             < property name = "targetPackage" value = "com.yuan.mybatis.mbg.util" /> 
 
             < property name = "targetProject" value = "${targetProject}" /> 
 
         </ plugin
 
         < commentGenerator
 
             < property name = "suppressAllComments" value = "true" /> 
 
         </ commentGenerator
 
         < jdbcConnection driverClass = "${driverClass}"  
 
             connectionURL = "${connectionURL}" userId = "${userId}" password = "${password}"
 
         </ jdbcConnection
 
         < javaTypeResolver
 
             < property name = "forceBigDecimals" value = "false" /> 
 
         </ javaTypeResolver
 
    
 
         < javaModelGenerator targetPackage = "${modelPackage}"  
 
             targetProject = "${targetProject}"
 
             < property name = "enableSubPackages" value = "true" /> 
 
         </ javaModelGenerator
 
    
 
         < sqlMapGenerator targetPackage = "${sqlMapperPackage}"  
 
             targetProject = "${targetProject}"
 
             < property name = "enableSubPackages" value = "true" /> 
 
         </ sqlMapGenerator
 
    
 
         < javaClientGenerator type = "XMLMAPPER"  
 
             targetPackage = "${daoMapperPackage}" targetProject = "${targetProject}"
 
             < property name = "enableSubPackages" value = "true" /> 
 
         </ javaClientGenerator
 
         < table schema = "minghan" tableName = "sys_group" domainObjectName = "Group"
 
             < generatedKey column = "groupId" sqlStatement = "mysql"  
 
                 identity = "true" /> 
 
         </ table
 
         < table schema = "minghan" tableName = "sys_admin" domainObjectName = "Admin"  
 
             enableCountByExample = "false" enableUpdateByExample = "false"  
 
             enableDeleteByExample = "false" enableSelectByExample = "false"  
 
             selectByExampleQueryId = "false"
 
         </ table
 
    
 
     </ context
 
</ generatorConfiguration >
    

其中的 properties 元素里引用了一个 generatorConfig.properties 配置文件是为了方便移植的时候 , 只需修改 resource 的路径值和 generatorConfig.properties 里的值即进行生成操作 .

generatorConfig.properties 代码如下 :

Properties 代码   收藏代码

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classPath=D\:/ylink/myeclipse/MBG/lib/mysql-connector-java-5.0.7-bin.jar 
 
targetProject=D\:/ylink/myeclipse/MBG/src 
 
driverClass=com.mysql.jdbc.Driver 
 
connectionURL=jdbc\:mysql\://127.0.0.1\:3306/minghan?useUnicode\=true&amp;characterEncoding\=UTF-8 
 
userId=root 
 
password=root 
 
modelPackage=com.yuan.mybatis.mbg.model 
 
sqlMapperPackage=com.yuan.mybatis.mbg.model.mapper 
 
daoMapperPackage=com.yuan.mybatis.mbg.dao.mapper

 

  其中 , targetProject 是工程的源代码存放位置

classPath 是数据库驱动包的位置 , modelPackage 是存放 model 实体的包 对应数据库表 , sqlMapperPackage 是存放实体映射的 XML 配置文件 , daoMapperPackage 是存放 Mapper 接口的地方 .

注意 要事先建立这些包才可以生成 .

如果不想生成 mybatis 的注释信息 可以将 commentGenerator 里的 suppressAllComments 的值设为 true,

table 元素对应数据库表 .

<table schema="minghan" tableName="sys_admin" domainObjectName="Admin"  

     enableCountByExample="false" enableUpdateByExample="false"  

     enableDeleteByExample="false" enableSelectByExample="false"

    selectByExampleQueryId="false">

</table> 

  schema 即为数据库名 , tableName 为对应的数据库表 , domainObjectName 是要生成的实体类 如果想要 mapper 配置文件加入 sql where 条件查询 可以将 enableCountByExample 等设为 true,  这样就会生成一个对应 domainObjectName Example , enableCountByExample 等设为 false 就不会生成对应的 Example 类了 .

3. 运行

配置文件配好了之后 , 进行生成代码 既可以使用命令的方式 也可以自已写一个带 main 的类来运行 下面提供了一个带 main 的运行类

MyBatisGeneratorTool.java

Java 代码   收藏代码

  1. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    package com.yuan.mybatis.mbg.util; 
        
     
    import java.io.File; 
     
    import java.io.IOException; 
     
    import java.sql.SQLException; 
     
    import java.util.ArrayList; 
     
    import java.util.List; 
     
        
     
    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; 
     
        
     
    public class MyBatisGeneratorTool { 
     
         public static void main(String[] args) { 
     
             List<String> warnings = new ArrayList<String>(); 
     
             boolean overwrite = true
     
             String genCfg = "/generatorConfig.xml" ; //src的一级目录下 
     
             File configFile = new File(MyBatisGeneratorTool. class .getResource(genCfg).getFile()); 
     
             ConfigurationParser cp = new ConfigurationParser(warnings); 
     
             Configuration config = null
     
             try
     
                 config = cp.parseConfiguration(configFile); 
     
             } catch (IOException e) { 
     
                 e.printStackTrace(); 
     
             } catch (XMLParserException e) { 
     
                 e.printStackTrace(); 
     
            
     
             DefaultShellCallback callback = new DefaultShellCallback(overwrite); 
     
             MyBatisGenerator myBatisGenerator = null
     
             try
     
                 myBatisGenerator = new MyBatisGenerator(config, callback, warnings); 
     
             } catch (InvalidConfigurationException e) { 
     
                 e.printStackTrace(); 
     
            
     
             try
     
                 myBatisGenerator.generate( null ); 
     
             } catch (SQLException e) { 
     
                 e.printStackTrace(); 
     
             } catch (IOException e) { 
     
                 e.printStackTrace(); 
     
             } catch (InterruptedException e) { 
     
                 e.printStackTrace(); 
     
            
     
        
     
    }

  运行此类即可生成对应于数据库表的实体类 , Mapper 配置文件 , Mapper 接口 生成后可以测试其可用性 .

使用命令的方式运行:

   java -jar mybatis-generator-core-x.x.x.jar -configfile generatorConfig.xml -overwrite

4. 其他学习网址推荐

推荐一个比较好的 mybatis-generator 的教学网址:

http://www.cnblogs.com/harrychinese/archive/2012/01/09/learn_mybatis.html

MyBatis使用Generator自动生成代码


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论