1. 程式人生 > >使用MyBatisGenerator自動生成Mybatis的相關代碼

使用MyBatisGenerator自動生成Mybatis的相關代碼

args pool mage ransac http manage build values 令行

一、構建一個環境:

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. <generatorConfiguration>
  6. <classPathEntry location="mysql-connector-java-5.1.6-bin.jar" />
  7. <context id="DB2Tables" targetRuntime="MyBatis3">
  8. <commentGenerator>
  9. <property name="suppressDate" value="true" />
  10. </commentGenerator>
  11. <jdbcConnection driverClass="com.mysql.jdbc.Driver"
  12. connectionURL="jdbc:mysql://localhost/test" userId="qgd" password="123456">
  13. </jdbcConnection>
  14. <javaTypeResolver>
  15. <property name="forceBigDecimals" value="false" />
  16. </javaTypeResolver>
  17. <javaModelGenerator targetPackage="test.model"
  18. targetProject="../src/main/java">
  19. <property name="enableSubPackages" value="true" />
  20. <property name="trimStrings" value="true" />
  21. </javaModelGenerator>
  22. <sqlMapGenerator targetPackage="test.dao"
  23. targetProject="../src/main/java">
  24. <property name="enableSubPackages" value="true" />
  25. </sqlMapGenerator>
  26. <javaClientGenerator type="XMLMAPPER"
  27. targetPackage="test.dao" targetProject="../src/main/java">
  28. <property name="enableSubPackages" value="true" />
  29. </javaClientGenerator>
  30. <table tableName="pet" domainObjectName="Pet">
  31. </table>
  32. </context>
  33. </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. import java.io.Reader;
  3. import java.util.List;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. import test.dao.PetMapper;
  9. import test.model.Pet;
  10. import test.model.PetExample;
  11. public class Test {
  12. public static void main(String[] args) throws Exception {
  13. String resource = "MapperConfig.xml";
  14. Reader reader = Resources.getResourceAsReader(resource);
  15. SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
  16. SqlSession sqlSession = sqlMapper.openSession();
  17. PetExample pet = new PetExample();
  18. pet.or().andDeathIsNotNull();
  19. try {
  20. PetMapper mapper = sqlSession.getMapper(PetMapper.class);
  21. List<Pet> allRecords = mapper.selectByExample(pet);
  22. for (Pet s : allRecords)
  23. System.out.println(s);
  24. } finally {
  25. sqlSession.close();
  26. }
  27. }
  28. }

這樣就可以打印出相應的查詢結果信息了。

四、小結

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

本文中只是用到了mybatis-generator 的一部分功能,mybatis-generator 生成代碼的方式還包括ant或Maven腳本,或者直接使用java API生成;另外通過修改配置文件,generator還可以指定表的生成細節,並可以添加插件。其功能文檔在generator的分發包的doc文件夾下有更詳細的介紹。

使用MyBatisGenerator自動生成Mybatis的相關代碼