zoukankan      html  css  js  c++  java
  • 使用MyBatisGenerator自动生成Mybatis的相关代码

    一、构建一个环境: 

    1. 首先创建一个表:

    Sql代码  收藏代码
    1. CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);  

     

    2. 然后注入数据

    Sql代码  收藏代码
    1. insert into pet values('Fluffy', 'Harold', 'cat', 'f', '1993-02-04', null);  
    2. insert into pet values('Claws', 'Gwen', 'cat', 'm', '1994-03-17', null);  
    3. insert into pet values('Buffy', 'Harold', 'dog', 'f', '1989-05-13', null);  
    4. insert into pet values('Fang', 'Benny', 'dog', 'm', '1990-08-27', null);  
    5. insert into pet values('Bowser', 'Diane', 'dog', 'm', '1979-08-31', '1995-07-29');  
    6. insert into pet values('Chirpy', 'Gwen', 'bird', 'f', '1998-09-11', null);  
    7. insert into pet values('Whistler', 'Gwen', 'bird', null, '1997-12-09', null);  
    8. insert into pet values('Slim', 'Benny', 'snake', 'm', '1996-04-29', null);  

    注:这里的sql例子来自 http://dev.mysql.com/doc/refman/5.5/en/creating-tables.html

    3. 在 Mybatis 主页 http://code.google.com/p/mybatis/ 上下载 Mybatis mybatis-generator-core [本文使用的是 1.3.0 版本]。当然运行 mybatis-generator 生成的代码还需要下载 mybatis 的 jar 包[本例使用的是 3.0.2 版本],和相关数据库的 jdbc [本文中使用的是MySql的jdbc] 。

    二、运行 mybatis-generator 

    1. 要运行 generator ,需要给 generator 提供一个配置文件,指定其生成的数据库的相关信息。
    以下是一个示例:

    Xml代码  收藏代码
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <!DOCTYPE generatorConfiguration  
    3.   PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"  
    4.   "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">  
    5.   
    6. <generatorConfiguration>  
    7.     <classPathEntry location="mysql-connector-java-5.1.6-bin.jar" />  
    8.   
    9.     <context id="DB2Tables" targetRuntime="MyBatis3">  
    10.   
    11.         <commentGenerator>  
    12.             <property name="suppressDate" value="true" />  
    13.         </commentGenerator>  
    14.   
    15.         <jdbcConnection driverClass="com.mysql.jdbc.Driver"  
    16.             connectionURL="jdbc:mysql://localhost/test" userId="qgd" password="123456">  
    17.         </jdbcConnection>  
    18.   
    19.         <javaTypeResolver>  
    20.             <property name="forceBigDecimals" value="false" />  
    21.         </javaTypeResolver>  
    22.   
    23.         <javaModelGenerator targetPackage="test.model"  
    24.             targetProject="../src/main/java">  
    25.             <property name="enableSubPackages" value="true" />  
    26.             <property name="trimStrings" value="true" />  
    27.         </javaModelGenerator>  
    28.   
    29.         <sqlMapGenerator targetPackage="test.dao"  
    30.             targetProject="../src/main/java">  
    31.             <property name="enableSubPackages" value="true" />  
    32.         </sqlMapGenerator>  
    33.   
    34.         <javaClientGenerator type="XMLMAPPER"  
    35.             targetPackage="test.dao" targetProject="../src/main/java">  
    36.             <property name="enableSubPackages" value="true" />  
    37.         </javaClientGenerator>  
    38.   
    39.         <table tableName="pet" domainObjectName="Pet">  
    40.         </table>  
    41.   
    42.     </context>  
    43. </generatorConfiguration>  

    这个配置文件提供了 mybatis-generator所需要的参数信息:

      * 其中classPathEntry 是引用的jdbc的类路径,这里将jdbc jar和generator的jar包放在一起了;
      * commentGenerator 是用来除去时间信息的,这在配合类似subversion的代码管理工具时使用很有效,因为可以减少没有必要的注释迁入;
      * jdbcConnection是指定的jdbc的连接信息;
      * javaTypeResolver式类型转换的信息,这里并没有用到;
      * javaModelGenerator是模型的生成信息,这里将指定这些Java model类的生成路径;
      * sqlMapGenerator是mybatis 的sqlMapper XML文件的生成信息,包括生成路径等;
      * javaClientGenerator是应用接口的生成信息;
      * table是用户指定的被生成相关信息的表,它必须在指定的jdbc连接中已经被建立。

    2. mybatis-generator 有多种运行方式,最简单的就是命令行的方式,只需要指定相应的配置文件的路径即可:

    Java代码  收藏代码
    1. java -jar mybatis-generator-core-1.3.0.jar -configfile ../src/main/resource/config.xml -overwrite  

    运行后生成的代码包括模型类 test.model.Pet 和 test.model.PetExample , test.dao.PetMapper 接口以及其相对应的 xml 映射文件,在这里就不在赘述了。

    三、使用 mybatis-generator 生成的代码 

    1. 现在我们要利用这些生成的代码,首先我们需要一个关于所有映射的配置文件。需要我们手写如下:【不知道为什么generator没有选择自动生成这个文件,毕竟这些信息generator都可以得到】

    Xml代码  收藏代码
    1. <?xml version="1.0" encoding="UTF-8" ?>  
    2. <!DOCTYPE configuration  
    3.     PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
    4.     "http://mybatis.org/dtd/mybatis-3-config.dtd">  
    5. <configuration>  
    6.     <environments default="development">  
    7.         <environment id="development">  
    8.             <transactionManager type="JDBC" />  
    9.             <dataSource type="POOLED">  
    10.                 <property name="driver" value="com.mysql.jdbc.Driver" />  
    11.                 <property name="url" value="jdbc:mysql://localhost/test" />  
    12.                 <property name="username" value="qgd" />  
    13.                 <property name="password" value="123456" />  
    14.             </dataSource>  
    15.         </environment>  
    16.     </environments>  
    17.     <mappers>  
    18.         <mapper resource="test/dao/PetMapper.xml" />  
    19.     </mappers>  
    20. </configuration>  

     

    2. 另外还要使用然后我们还需要一个Main示例方法来调用这些已生成的代码:

    Java代码  收藏代码
    1. package test;  
    2.   
    3. import java.io.Reader;  
    4. import java.util.List;  
    5.   
    6. import org.apache.ibatis.io.Resources;  
    7. import org.apache.ibatis.session.SqlSession;  
    8. import org.apache.ibatis.session.SqlSessionFactory;  
    9. import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
    10.   
    11. import test.dao.PetMapper;  
    12. import test.model.Pet;  
    13. import test.model.PetExample;  
    14.   
    15. public class Test {  
    16.   
    17.     public static void main(String[] args) throws Exception {  
    18.         String resource = "MapperConfig.xml";  
    19.         Reader reader = Resources.getResourceAsReader(resource);  
    20.         SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);  
    21.         SqlSession sqlSession = sqlMapper.openSession();  
    22.   
    23.         PetExample pet = new PetExample();  
    24.         pet.or().andDeathIsNotNull();  
    25.         try {  
    26.             PetMapper mapper = sqlSession.getMapper(PetMapper.class);  
    27.             List<Pet> allRecords = mapper.selectByExample(pet);  
    28.             for (Pet s : allRecords)  
    29.                 System.out.println(s);  
    30.         } finally {  
    31.             sqlSession.close();  
    32.         }  
    33.     }  
    34. }  

    这样就可以打印出相应的查询结果信息了。

    四、小结 

    该示例的完整的Eclipse工程见附件mybatis-generator-usage.zip,其中已经包含了示例需要使用的jar包。

    本文中只是用到了mybatis-generator 的一部分功能,mybatis-generator 生成代码的方式还包括ant或Maven脚本,或者直接使用java API生成;另外通过修改配置文件,generator还可以指定表的生成细节,并可以添加插件。其功能文档在generator的分发包的doc文件夹下有更详细的介绍。

  • 相关阅读:
    datetime模块
    python正则表达式练习题
    Python入门——turtle库的使用
    Python入门——Python程序语法元素
    Python入门——eval() 函数
    Python入门——实例1_温度转换
    Python入门——编程方式
    Python入门——程序的基本编写方法
    Python入门——编译和解释
    SQL中isnull、ifnull和nullif函数用法
  • 原文地址:https://www.cnblogs.com/fkeyta/p/7792572.html
Copyright © 2011-2022 走看看