1. 什麼是逆向工程
mybatis官方提供了一個逆向工程,可以針對單表自動生成mybatis執行所需要的代碼(包括mapper.xml、mapper.java、po..)。
2. 使用逆向工程
使用mybatis的逆向工程,需要導入逆向工程的jar包,我用的是mybatis-generator-core-1.3.2,已經上傳到下載下傳頻道了(點我下載下傳),下面開始總結一下mybatis逆向工程的使用步驟。
2.1 建立一個工程(重要)
我們要建立一個java工程,這個工程專門用來使用逆向工程生成代碼的.
因為在原來的工程中生成,但是有風險,因為mybatis是根據配置檔案來生成的(下面會說到),如果生成的路徑中有相同的檔案,那麼就會覆寫原來的檔案,這樣會有風險。
是以開發中一般都會建立一個java工程來生成,然後将生成的檔案拷貝到自己的工程中,這也不麻煩,而且很安全。如下:

從上圖中看,
1就是要執行的java代碼,執行它即可生成我們需要的代碼;
2 是執行過程中建立的包,這個包都可以在4的配置檔案中指定,最好是跟我們自己項目的包名一緻,後面就可以直接拷貝了,就不需要修改包名了;
3 就是jar包咯;
4 是配置檔案。下面會詳細分析。
2.1 生成代碼的配置檔案
mybatis逆向工程生成代碼需要一個配置檔案,名字随便起。然後mybatis會根據這個配置檔案中的配置,生成相應的代碼。下載下傳好了jar包後,裡面有幫助文檔,打開後裡面有配置檔案的模闆,這裡就不再贅述了,下面先把配置檔案寫好:
<?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="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自動生成的注釋 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--資料庫連接配接的資訊:驅動類、連接配接位址、使用者名、密碼 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root"
password="root">
</jdbcConnection>
<!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"
userId="yycg"
password="yycg">
</jdbcConnection> -->
<!-- 預設false,把JDBC DECIMAL 和 NUMERIC 類型解析為 Integer,為 true時把JDBC DECIMAL和NUMERIC類型解析為java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成PO類的位置,重要!! -->
<javaModelGenerator targetPackage="mybatis.po"
targetProject=".\src">
<!-- enableSubPackages:是否讓schema作為包的字尾 -->
<property name="enableSubPackages" value="false" />
<!-- 從資料庫傳回的值被清理前後的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射檔案生成的位置,重要!! -->
<sqlMapGenerator targetPackage="mybatis.mapper"
targetProject=".\src">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置,重要!! -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="mybatis.mapper"
targetProject=".\src">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定資料庫表,要生成哪些表,就寫哪些表,要和資料庫中對應,不能寫錯! -->
<table tableName="items"></table>
<table tableName="orders"></table>
<table tableName="orderdetail"></table>
<table tableName="user"></table>
</context>
</generatorConfiguration>
從上面的配置檔案中可以看出,配置檔案主要要做的幾件事是:
- 連接配接資料庫,這是必須的,要不然怎麼根據資料庫的表生成代碼呢?
- 指定要生成代碼的位置,要生成的代碼包括po類, mapper.xml和mapper.java
- 指定資料庫中想要生成哪些表
2.3 執行生成程式
配置檔案搞好了,然後就執行以下生成程式即可生成了,生成的java程式,下載下傳的逆向工程文檔中都有示例,如下:
public class GeneratorSqlmap {
public void generator() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//指向逆向工程配置檔案
File configFile = new File("generatorConfig.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);
}
public static void main(String[] args) throws Exception {
try {
GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}
運作一下即可,運作完了後重新整理一下工程,就可以看到最新生成的代碼了。
這裡可以看出有個細節,每個po類多了一個東西,就是xxxExample.java,這個類是給使用者自定義sql是用的,後面我會提到。到這裡就生成好了,下面我們就把生成的代碼拷貝到自己的工程使用了,為了簡便,這裡我就拷貝ItemsMapper.java/ItemsMapper.xml/Items.java/ItemsExample.java這一類的,其他都一樣。
3. 測試生成的代碼
我們針對ItemsMapper.java建立一個測試類,測試其中的幾個方法:
public class ItemsMapperTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void setUp() throws Exception {
// 建立sqlSessionFactory
String resource = "SqlMapConfig.xml"; // mybatis配置檔案
// 得到配置檔案的流
InputStream inputStream = Resources.getResourceAsStream(resource);
// 建立會話工廠SqlSessionFactory,要傳入mybaits的配置檔案的流
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
//普通的插入,跟我們之前的插入是一樣的
@Test
public void testInsert() {
SqlSession sqlSession = sqlSessionFactory.openSession();
ItemsMapper itemsMapper = sqlSession.getMapper(ItemsMapper.class);
Items items = new Items();
items.setName("手機");
items.setPrice(f);
items.setCreatetime(new Date());
itemsMapper.insert(items);
sqlSession.commit();
//還有一個insertSelective(items);方法,是插入的項不為空時,才将那個字段拼接到sql中
//可以下自動生成的xml檔案就知道了。
}
//自定義查詢
@Test
public void testSelectByExample() {
SqlSession sqlSession = sqlSessionFactory.openSession();
ItemsMapper itemsMapper = sqlSession.getMapper(ItemsMapper.class);
//自定義查詢,這就用到了ItemsExample類了,裡面有個Criteria内部類,專門用來封裝自定義查詢條件的
ItemsExample itemsExample = new ItemsExample();
ItemsExample.Criteria criteria = itemsExample.createCriteria();
//andNameEqualTo相當于在sql中拼接一個“AND name='背包'”
//還有其他很多方法,都是用來自定義查詢條件的,可以自己看一下不同的方法
criteria.andNameEqualTo("背包");
List<Items> itemsList = itemsMapper.selectByExample(itemsExample);
System.out.println(itemsList);
}
//根據主鍵查詢,跟原來一樣
@Test
public void testSelectByPrimaryKey() {
ItemsMapper itemsMapper = sqlSessionFactory.openSession().getMapper(ItemsMapper.class);
Items items = itemsMapper.selectByPrimaryKey();
System.out.println(items);
}
//根據主鍵更新item,跟原來一樣
@Test
public void testUpdateByPrimaryKey() {
SqlSession sqlSession = sqlSessionFactory.openSession();
ItemsMapper itemsMapper = sqlSession.getMapper(ItemsMapper.class);
Items items = itemsMapper.selectByPrimaryKey();
items.setPrice(f);
itemsMapper.updateByPrimaryKey(items);
sqlSession.commit();
}
}
相關閱讀:http://blog.csdn.net/column/details/smybatis.html
學習筆記源碼下載下傳位址:https://github.com/eson15/MyBatis_Study