使用MyBatisGenerator自動生成Mybatis的相關代碼
一、構建一個環境:
1. 首先創建一個表:
Sql代碼
- CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);
2. 然後註入數據
Sql代碼- insert into pet values(‘Fluffy‘, ‘Harold‘, ‘cat‘, ‘f‘, ‘1993-02-04‘, null);
- insert into pet values(‘Claws‘, ‘Gwen‘, ‘cat‘, ‘m‘, ‘1994-03-17‘, null);
- insert into pet values(‘Buffy‘, ‘Harold‘, ‘dog‘, ‘f‘, ‘1989-05-13‘, null);
- insert into pet values(‘Fang‘, ‘Benny‘, ‘dog‘, ‘m‘, ‘1990-08-27‘, null);
- insert into pet values(‘Bowser‘, ‘Diane‘, ‘dog‘, ‘m‘, ‘1979-08-31‘, ‘1995-07-29‘);
- insert into pet values(‘Chirpy‘, ‘Gwen‘, ‘bird‘, ‘f‘, ‘1998-09-11‘, null);
- insert into pet values(‘Whistler‘, ‘Gwen‘, ‘bird‘, null, ‘1997-12-09‘, null);
- 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 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 location="mysql-connector-java-5.1.6-bin.jar" />
- <context id="DB2Tables" targetRuntime="MyBatis3">
- <commentGenerator>
- <property name="suppressDate" value="true" />
- </commentGenerator>
- <jdbcConnection driverClass="com.mysql.jdbc.Driver"
- connectionURL="jdbc:mysql://localhost/test" userId="qgd" password="123456">
- </jdbcConnection>
- <javaTypeResolver>
- <property name="forceBigDecimals" value="false" />
- </javaTypeResolver>
- <javaModelGenerator targetPackage="test.model"
- targetProject="../src/main/java">
- <property name="enableSubPackages" value="true" />
- <property name="trimStrings" value="true" />
- </javaModelGenerator>
- <sqlMapGenerator targetPackage="test.dao"
- targetProject="../src/main/java">
- <property name="enableSubPackages" value="true" />
- </sqlMapGenerator>
- <javaClientGenerator type="XMLMAPPER"
- targetPackage="test.dao" targetProject="../src/main/java">
- <property name="enableSubPackages" value="true" />
- </javaClientGenerator>
- <table tableName="pet" domainObjectName="Pet">
- </table>
- </context>
- </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 -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 version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE configuration
- PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC" />
- <dataSource type="POOLED">
- <property name="driver" value="com.mysql.jdbc.Driver" />
- <property name="url" value="jdbc:mysql://localhost/test" />
- <property name="username" value="qgd" />
- <property name="password" value="123456" />
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <mapper resource="test/dao/PetMapper.xml" />
- </mappers>
- </configuration>
2. 另外還要使用然後我們還需要一個Main示例方法來調用這些已生成的代碼:
Java代碼- package test;
- import java.io.Reader;
- import java.util.List;
- import org.apache.ibatis.io.Resources;
- import org.apache.ibatis.session.SqlSession;
- import org.apache.ibatis.session.SqlSessionFactory;
- import org.apache.ibatis.session.SqlSessionFactoryBuilder;
- import test.dao.PetMapper;
- import test.model.Pet;
- import test.model.PetExample;
- public class Test {
- public static void main(String[] args) throws Exception {
- String resource = "MapperConfig.xml";
- Reader reader = Resources.getResourceAsReader(resource);
- SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
- SqlSession sqlSession = sqlMapper.openSession();
- PetExample pet = new PetExample();
- pet.or().andDeathIsNotNull();
- try {
- PetMapper mapper = sqlSession.getMapper(PetMapper.class);
- List<Pet> allRecords = mapper.selectByExample(pet);
- for (Pet s : allRecords)
- System.out.println(s);
- } finally {
- sqlSession.close();
- }
- }
- }
這樣就可以打印出相應的查詢結果信息了。
四、小結
該示例的完整的Eclipse工程見附件mybatis-generator-usage.zip,其中已經包含了示例需要使用的jar包。
本文中只是用到了mybatis-generator 的一部分功能,mybatis-generator 生成代碼的方式還包括ant或Maven腳本,或者直接使用java API生成;另外通過修改配置文件,generator還可以指定表的生成細節,並可以添加插件。其功能文檔在generator的分發包的doc文件夾下有更詳細的介紹。
使用MyBatisGenerator自動生成Mybatis的相關代碼