一、創(chuàng)建一個(gè)逆向工程的步驟
1、環(huán)境的準(zhǔn)備
(1)广恢、準(zhǔn)備mybatis-config.xml
文件:
<?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>
<properties resource="dbconfig.properties"></properties>
<settings>
<setting name="jdbcTypeForNull" value="NULL"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
<setting name="cacheEnabled" value="true"/>
</settings>
<!--typeAliases:別名處理器欣孤,可以為我們的Java類型取別名-->
<typeAliases>
<package name="com.cerr.mybatis"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 批量注冊(cè) -->
<package name="com.cerr.dao"/>
</mappers>
</configuration>
(2)馋没、創(chuàng)建數(shù)據(jù)庫配置文件dbconfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true
jdbc.username=root
jdbc.password=root
(3)、準(zhǔn)備其它相關(guān)的包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cerr</groupId>
<artifactId>mybatis-1</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13-beta-3</version>
</dependency>
</dependencies>
</project>
2降传、導(dǎo)入相關(guān)的包
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
3篷朵、配置逆向工程的xml文件
我們創(chuàng)建一個(gè)mbg.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>
<context id="DB2Tables" targetRuntime="MyBatis3Simple">
<!-- jdbcConnection:指定如何連接到目標(biāo)數(shù)據(jù)庫-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis"
userId="root"
password="root">
</jdbcConnection>
<!--javaTypeResolver:定義類型解析器-->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!--
javaModelGenerator:指定JavaBean的生成策略
targetPackage:指定目標(biāo)類名
targetProject:指定目標(biāo)工程
-->
<javaModelGenerator targetPackage="com.cerr.bean" targetProject=".\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--
sqlMapGenerator:sql映射生成策略
-->
<sqlMapGenerator targetPackage="com.cerr.dao" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!--
javaClientGenerator:指定mapper接口所在的位置
-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.cerr.dao" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 指定要逆向生成的表:根據(jù)表要?jiǎng)?chuàng)建JavaBean-->
<table tableName="tb1_employee" domainObjectName="Employee"></table>
<table tableName="tbl_dept" domainObjectName="Department"></table>
</context>
</generatorConfiguration>
4、創(chuàng)建方法來運(yùn)行我們配置的逆向工程
@Test
public void test1() throws Exception{
List <String> warnings = new ArrayList <String>();
boolean overwrite = true;
File configFile = new File("mbg.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
運(yùn)行后結(jié)果如下:
二婆排、分析
1声旺、指定創(chuàng)建的映射文件
targetRuntime
表示創(chuàng)建的映射文件的策略,若其值為MyBatis3Simple
表明生成的是一個(gè)簡(jiǎn)單的映射文件段只;若為MyBatis
則表明生成的是一個(gè)復(fù)雜的映射文件腮猖。
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3Simple">
</context>
</generatorConfiguration>
2、配置需要連接的數(shù)據(jù)庫
jdbcConnection
配置連接的數(shù)據(jù)庫赞枕,其中driverClass
指定數(shù)據(jù)庫驅(qū)動(dòng)澈缺;connectionURL
指定數(shù)據(jù)庫的url
;userId
指定數(shù)據(jù)庫用戶名炕婶;password
指定數(shù)據(jù)庫用戶密碼姐赡。
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis"
userId="root"
password="root">
</jdbcConnection>
3、配置類型解析器
javaTypeResolver
指定類型解析器柠掂。
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
4项滑、指定JavaBean的生成策略
javaModelGenerator
用于指定JavaBean的生成策略。其中targetPackage
指定目標(biāo)類名涯贞,targetProject
指定目標(biāo)工程枪狂。
<javaModelGenerator targetPackage="com.cerr.bean" targetProject=".\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
5危喉、指定sql映射生成策略
sqlMapGenerator
用于指定sql映射的生成策略,其中targetPackage指定目標(biāo)類名州疾,
targetProject`指定目標(biāo)工程姥饰。
<sqlMapGenerator targetPackage="com.cerr.dao" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
6、指定mapper接口的生成策略
javaClientGenerator
用于指定mapper接口的生成策略孝治,其中targetPackage指定目標(biāo)類名列粪,
targetProject`指定目標(biāo)工程。
<javaClientGenerator type="XMLMAPPER" targetPackage="com.cerr.dao" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
7谈飒、指定生成的表
<table>
可用于指定想生成JavaBean的表岂座,MyBatis根據(jù)表的配置來生成JavaBean。tableName
屬性用于指定表名杭措,domainObjectName
屬性用于指定生成的JavaBean的名字费什。
<table tableName="tb1_employee" domainObjectName="Employee"></table>
<table tableName="tbl_dept" domainObjectName="Department"></table>
三、使用逆向工程來進(jìn)行復(fù)雜的查詢
我們先將之前自動(dòng)生成的文件都刪除手素,然后將配置文件中的targetRuntime
屬性更改為MyBatis3
鸳址。然后再調(diào)用上面的生成方法進(jìn)行生成。
生成成功后文件如下:
我們可以看到多了個(gè)DepartmentExample和EmployeeExample泉懦,并且響應(yīng)的Mapper里面的方法也是多了不少稿黍。
接下來我們來進(jìn)行復(fù)雜的條件查詢,我們直接編寫方法如下:
@Test
public void test2() throws IOException {
SqlSessionFactory factory = getSqlSessionFactory();
SqlSession session = factory.openSession();
try{
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
List<Employee> employees ;
EmployeeExample example = new EmployeeExample();
EmployeeExample.Criteria criteria = example.createCriteria();
//拼裝條件
criteria.andLastNameLike("%e%");
criteria.andGenderEqualTo("1");
//另一個(gè)
EmployeeExample.Criteria criteria1 = example.createCriteria();
criteria1.andEmailEqualTo("%e%");
//拼接上or
example.or(criteria1);
employees = mapper.selectByExample(example);
for (Employee e : employees){
System.out.println(e.getId());
}
}finally {
session.close();
}
}
在這個(gè)方法中崩哩,我們想查詢的sql條件為如下:
select id, last_name, gender, email, d_id from tb1_employee WHERE ( last_name like ? and gender = ? ) or( email = ? )
我們首先應(yīng)該先實(shí)例化一個(gè)EmployeeExample
對(duì)象巡球,然后再去使用這個(gè)對(duì)象去新建兩個(gè)Criteria
對(duì)象,對(duì)于每一個(gè)Criteria
對(duì)象邓嘹,我們可以添加其sql中的and
條件語句酣栈。因?yàn)?code>Criteria對(duì)象不能添加or
條件語句,因此我們需要新建兩個(gè)Criteria
對(duì)象汹押,對(duì)于那個(gè)要拼接or
的對(duì)象矿筝,只需調(diào)用example
對(duì)象的or()
方法即可,即上述代碼中的example.or(criteria1);
棚贾,然后使用selectByExample(example)
進(jìn)行查詢窖维,如果此時(shí)想查詢所有的話,那么selectByExample(null)
即可鸟悴。運(yùn)行上述的代碼后陈辱,發(fā)出的sql如下: