本文將簡要介紹怎樣利用Mybatis Generator自動生成Mybatis的相關代碼: html
1、構建一個環境: java
1. 首先建立一個表: mysql
1. CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), birth DATE, death DATE); sql
2. 而後注入數據 數據庫
1. insert into pet values('Fluffy', 'Harold', 'cat', 'f', '1993-02-04', null); apache
2. insert into pet values('Claws', 'Gwen', 'cat', 'm', '1994-03-17', null); session
3. insert into pet values('Buffy', 'Harold', 'dog', 'f', '1989-05-13', null); mybatis
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] 。
2、運行 mybatis-generator
1. 要運行 generator ,須要給 generator 提供一個配置文件,指定其生成的數據庫的相關信息。
如下是一個示例:
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 有多種運行方式,最簡單的就是命令行的方式,只須要指定相應的配置文件的路徑便可:
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 映射文件,在這裏就不在贅述了。
3、使用 mybatis-generator 生成的代碼
1. 如今咱們要利用這些生成的代碼,首先咱們須要一個關於全部映射的配置文件。須要咱們手寫以下:【不知道爲何generator沒有選擇自動生成這個文件,畢竟這些信息generator均可以獲得】
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示例方法來調用這些已生成的代碼:
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. }
這樣就能夠打印出相應的查詢結果信息了。
4、小結
該示例的完整的Eclipse工程見附件mybatis-generator-usage.zip,其中已經包含了示例須要使用的jar包。
本文中只是用到了mybatis-generator 的一部分功能,mybatis-generator 生成代碼的方式還包括ant或Maven腳本,或者直接使用java API生成;另外經過修改配置文件,generator還能夠指定表的生成細節,並能夠添加插件。其功能文檔在generator的分發包的doc文件夾 下有更詳細的介紹。
這裏使用的表示沒有主鍵的表,針對有一個主鍵或多個主鍵的表,mybatis-generator的生成的內容也有所不一樣,感興趣的讀者能夠自行試驗一下。
本文將簡要介紹怎樣利用Spring 整合 Mybatis Generator自動生成的代碼:
關於Mybatis Generator自動生成怎樣自動生成代碼,請參考這篇文章:使用Mybatis Generator自動生成Mybatis相關代碼 ,本篇文章將接着上一篇文章的例子繼續。
1、準備環境
1. 下載jar包:首先要在Mybatis網站中下載相應的 jar包mybatis-spring-1.0.0-RC2-bundle.zip http://code.google.com/p/mybatis/downloads/list?can=3&q=Product%3DSpring
另外固然還須要Spring的jar包,本文中用到版本的是3.0.4
2. 添加jar包:要使用mybatis-spring-1.0.0-RC1.jar,除了要在構建路徑上添加jdbc包、Mybatis的包外,還須要添加 Spring的asm, beans, context, core, expression, jdbc, transaction這幾個包,固然還要包括apache-commons-logging。
2、運行 mybatis-generator
爲了方便運行,在本示例中將Mybatis Generator的代碼生成用ant腳本的方式給出:
1. <?xml version="1.0" encoding="UTF-8"?>
2. <project default="genfiles" basedir=".">
3. <target name="genfiles" description="Generate the files">
4. <taskdef name="mbgenerator" classname="org.mybatis.generator.ant.GeneratorAntTask"
5. classpath="mybatis-generator-core-1.3.0.jar" />
6. <mbgenerator overwrite="true" configfile="src/main/resource/config.xml"
7. verbose="false">
8. </mbgenerator>
9. </target>
10. </project>
不過在運行示例時請修改config.xml中jdbc jar包的位置 ,由於示例中使用的是絕對路徑,而沒有成功的轉成相對路徑,如有誰成功的轉成相對路徑的話,請留言相教,謝謝。
3、使用 mybatis-generator 生成的代碼
在使用Mybatis Generator自動生成Mybatis相關代碼 的文章中,我還不明白爲何要手寫一個關於全部映射的配置文件。使用Spring後我知道了,原來在Spring中使用mybatis-generator 生成的代碼,根本就不須要這個配置文件,只要在Spring的context文件中配置相應的信息便可。
下面是context配置示例:
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans xmlns="http://www.springframework.org/schema/beans"
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4. xmlns:context="http://www.springframework.org/schema/context"
5. xsi:schemaLocation="
6. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
7. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
8. default-autowire="byName">
9.
10. <bean
11. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
12. <property name="locations" value="classpath:datasource.properties" />
13. </bean>
14.
15. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
16. <property name="driverClassName" value="${jdbc.driverClassName}" />
17. <property name="url" value="${jdbc.url}" />
18. <property name="username" value="${jdbc.username}" />
19. <property name="password" value="${jdbc.password}" />
20. </bean>
21.
22. <bean id="transactionManager"
23. class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
24. <property name="dataSource" ref="dataSource" />
25. </bean>
26.
27. <!-- beware that mapper-config.xml is not needed if you use injected mappers -->
28. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
29. <!-- <property name="configLocation" value="classpath:MapperConfig.xml" /> -->
30. <property name="dataSource" ref="dataSource" />
31. </bean>
32.
33. <bean id="petMapper1" class="org.mybatis.spring.MapperFactoryBean">
34. <!-- SqlSessionFactory property is autowired -->
35. <property name="mapperInterface" value="test.dao.PetMapper" />
36. </bean>
37.
38. </beans>
能夠看到sqlSessionFactory bean中的configLocation屬性被註釋掉了,不過絲絕不影響對相應dao接口的使用。咱們只須要編寫下面的幾行代碼就已達到上篇文章示例中的相同效果:
1. package test;
2.
3. import org.springframework.context.ApplicationContext;
4. import org.springframework.context.support.ClassPathXmlApplicationContext;
5.
6. import test.dao.PetMapper;
7. import test.model.PetExample;
8.
9. public class Test {
10.
11. public static void main(String[] args) {
12. ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
13. PetExample pet = new PetExample();
14. pet.or().andDeathIsNotNull();
15. PetMapper map = (PetMapper) context.getBean("petMapper1");
16. System.out.println(map.selectByExample(pet));
17. }
18. }
這裏的給出的例子是結合Mybatis Generator自動生成的代碼儘可能少的手寫代碼的例子,可是靈活性上可能有不足。Mybatis的網站上提供了另外三種結合Spring使用的示例, 詳見 http://code.google.com/p/mybatis/source/browse/#svn/sub-projects/mybatis-spring/trunk/src/test 這裏就再也不贅述了。
4、小結
該示例的完整的Eclipse工程見附件mybatis-generator-usage2.zip,其中已經包含了示例須要使用的jar包。