MyIbatis學習 (一)--使用Generator自動生成代碼

Myibatis-Generator調用方式

Eclipse集成generator插件(常用)

1、在線安裝generator插件

打開eclipse,點擊Help>Software Update

選擇 "Available Software" 標籤,點擊 "Add Site" 按鈕

輸入以下信息:

Location:http://mybatis.googlecode.com/svn/sub-projects/generator/trunk/eclipse/UpdateSite/

點擊ok,自動進入 "mybatis generator Feature"

點擊“install”按鈕進行安裝。。。。mybatis generator 插件安裝完成

2、離線安裝generator插件


3、generator調用

generator插件安裝好之後,然後編寫生成配置文件generatorConfig.xml,eclipse中在這個文件上右鍵,就有Generate Mybatis/iBatis Artifacts,由此就可以生成代碼了。generatorConfig.xml文件詳細內容之後有示例,這裏先不貼出來,使用eclipse插件的方式有個不同就是targetProject的配置是項目名開頭的,比如其他配置是targetProject="src/main/java",在這裏就要是targetProject="項目名/src/main/java"。這裏爲什麼要加上項目名,可能是因爲eclipse插件是針對ide的,需要指定ide內是哪個項目。

GeneratorConfig.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 >
  <classPathEntry location="D:/ojdbc5-11.2.0.2.0.jar" />
  
  <context id="context1" >

  	<!-- 配置連接數據信息 -->  
    <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@192.168.1.233:1521:orcl" userId="cmss" password="cmss" />
    
 
	 <!-- 配置自動生成的Model的保存路徑與其它參數 --> 
	 <javaModelGenerator targetPackage="com.entity.main" targetProject="MyIbatisGeneratorForPage\src\main\java" />
	 <!-- 配置自動生成的Mappper.xml映射的保存路徑與其它參數 -->  	
	<sqlMapGenerator targetPackage="config.myibatis.xml" targetProject="MyIbatisGeneratorForPage\src\main\resources" />
	<!-- 配置自動生成的Mappper.java接口的保存路徑與其它參數 -->  	
	<javaClientGenerator targetPackage="com.dao" targetProject="MyIbatisGeneratorForPage\src\main\java" type="XMLMAPPER" />
	
  <!--    <table schema="" tableName="T_SYS_USER"></table>
    <table schema="" tableName="T_SYS_ROLE"></table>
    <table schema="" tableName="T_SYS_ORG"></table>
    <table schema="" tableName="T_SYS_ROLE_RES"></table>
    <table schema="" tableName="T_SYS_RESOURCE"></table>
    <table schema="" tableName="T_SYS_USER_ROLE"></table>
     -->
     <!-- 生成表對應的操作與實體對象 -->  
     <table schema="" tableName="T_CORE_ORG_HIS"></table>
  </context>
</generatorConfiguration>



Maven中集成Myibatis-Generator插件(常用)

自動生成代碼步驟:

1.創建一個Maven項目:File——New Project——Maven

2.在pom文件中,添加Myibatis-Generator插件,IDE會自動幫我們下載插件

(如果沒反應,可以點開右側Maven Project選項卡刷新以下)

<?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>Mybatis_Generator</groupId>
    <artifactId>Mybatis_Generator</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <finalName>mybatis_generator</finalName>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.0</version>
            </plugin>
        </plugins>
    </build>

</project>

3.在src/main/resource目錄下創建generatorConfig.xml文件

(官方配置以及說明:http://go.rritw.com/mybatis.github.io/generator/configreference/xmlconfig.html

<?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>
    <!--數據庫驅動jar -->
    <classPathEntry location="E:\mysql-connector-java-5.1.7-bin.jar" />

    <context id="DB2Tables" targetRuntime="Ibatis2Java5">
        <!--去除註釋 (true好像不起作用) -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!--數據庫連接 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/news"
                        userId="root"
                        password="">
        </jdbcConnection>
        <!--默認false
           Java type resolver will always use java.math.BigDecimal if the database column is of type DECIMAL or NUMERIC.
         -->
        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!--生成實體類 指定包名 以及生成的地址 (可以自定義地址,但是路徑不存在不會自動創建  使用Maven生成在target目錄下,會自動創建) -->
        <javaModelGenerator targetPackage="com.qianyan.model" targetProject="MAVEN">
            <property name="enableSubPackages" value="false" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!--生成SQLMAP文件 -->
        <sqlMapGenerator targetPackage="com.qianyan.persistence.ibatis"  targetProject="MAVEN">
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!--生成Dao文件 可以配置 type="XMLMAPPER"生成xml的dao實現  context id="DB2Tables" targetRuntime="MyBatis3"  -->
        <javaClientGenerator type="SPRING" targetPackage="com.qianyan.persistence.dao"  targetProject="MAVEN">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!--對應數據庫表 mysql可以加入主鍵自增 字段命名 忽略某字段等-->
        <table tableName="USER" domainObjectName="User" >
        </table>

    </context>
</generatorConfiguration>
4.點擊Maven Project——項目——Plugins——mybatis generator——Run Maven build

5.可以根據自己項目的配置,把生成的代碼拷貝到自己的項目中去


生成代碼使用

mybatis設計比較巧妙,Dao層就不用說了,這裏主要介紹下實體類User和UserExample

User類就是普通的實體類,定義了數據庫對應的字段,以及set/get方法

Example類是幹嘛的呢?用其它項目中的幾個例子還說明一下吧

1.比如在一個項目 我們要刪除某個小組下某個用戶的信息

public int deleteUserApplyInfo(long user_id,long team_id){
        StudyTeamUserApplyInfoExample ue = new StudyTeamUserApplyInfoExample();
        ue.createCriteria()
                .andUserIdEqualTo(new BigDecimal(user_id))
                .andTeamIdEqualTo(new BigDecimal(team_id));
        return studyTeamUserApplyInfoDAO.deleteByExample(ue);
    }

2.根據小組ID(非主鍵 更新小組信息)
public int updateStudyTeamInfo(StudyTeamInfo st){
        StudyTeamInfoExample ste = new StudyTeamInfoExample();
        ste.createCriteria().andTeamIdEqualTo(st.getTeamId());
        return studyTeamInfoDAO.updateByExampleSelective(st,ste);
    }
3.(1)模糊查詢並且排序 (2)大於等於某個分數 並且小於某個分數的查詢
public List<StudyTeamInfo> getStudyTeamInfoByName(String team_name){
        StudyTeamInfoExample se = new StudyTeamInfoExample();
        se.createCriteria().andTeamNameLike("%"+team_name+"%").andEnableEqualTo((short)1);
        se.setOrderByClause("team_score desc");
        List<StudyTeamInfo> ls = studyTeamInfoDAO.selectByExample(se);
        if(ls!=null&&ls.size()>0){
            return ls;
        }
        return null;
    }

Example中提供了Critertia,一種面向對象的查詢方式,並且根據實體類中字段的屬性,生成不同的操作。

當然你也可以根據實際需要直接使用實體類進行增刪改查


3. 直接運行jar(不常用)

爲了簡單起見,我把jar文件跟生成配置文件拷貝到一起mybatis-generator-core-1.3.2.jar和generatorConfig.xml,這裏的xml文件要加上jdbs驅動的路徑,在<generatorConfiguration>內部加上
<classPathEntry location="C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\5.1.24\mysql-connector-java-5.1.24.jar"/>
java -jar mybatis-generator-core-1.3.2.jar -configfile F:/xy/generatorConfig.xml -overwrite 
這樣也可正常生成。
這裏有段使用生成代碼的小例子,需要mybatis的配置文件MapperConfig.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>
     <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="test" />  
                <property name="password" value="test" /> 
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/com/xxx/mybatis/UsersMapper.xml"/>
    </mappers>
</configuration>


這裏的mapper內的屬性,netbeans會自動提示resources,應該是resource。坑爹的是,這裏寫s結尾的,報錯卻說mapper應該配置屬性resources,然後刪除s配置resource纔不會報錯。在下載的mybatis-generator-config_1_0.dtd文件可以看到正確的定義。然後java調用:
Reader reader = Resources.getResourceAsReader("config/MapperConfig.xml");
        SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlMapper.openSession();
        
        UsersExample example = new UsersExample();
        example.createCriteria().andPasswordIsNotNull();
        try {
            UsersMapper mapper = sqlSession.getMapper(UsersMapper.class);
            List<Users> users = mapper.selectByExample(example);
            for (Users u : users)  
                System.out.println(u.getUsername() + " -- " + u.getPassword()); 
        } finally {
            sqlSession.close();
        }


4. 自行編寫代碼(不常用)

官方有說明http://mybatis.org/generator/running/runningWithJava.html
直接上代碼
...
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
...
        List<String> warnings = new ArrayList<String>();
        final boolean overwrite = true;
        File configFile = new File("src/main/resources/config/generatorConfig.xml");
        //System.out.println("config fiel is in : " + configFile.getAbsoluteFile());
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration configuration = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator mybatisGenerator = new MyBatisGenerator(configuration, callback, warnings);
        mybatisGenerator.generate(null);

generatorConfig.xml配置詳解

現在針對generatorConfig.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>
	<!-- 引入配置文件 -->
	<properties resource="init.properties"/>
	
	<!-- 指定數據連接驅動jar地址 -->
	<classPathEntry location="${classPath}" />
	
	<!-- 一個數據庫一個context -->
	<context id="infoGuardian">
		<!-- 註釋 -->
		<commentGenerator >
			<property name="suppressAllComments" value="false"/><!-- 是否取消註釋 -->
			<property name="suppressDate" value="true" /> <!-- 是否生成註釋代時間戳-->
		</commentGenerator>
		
		<!-- jdbc連接 -->
		<jdbcConnection driverClass="${jdbc_driver}"
			connectionURL="${jdbc_url}" userId="${jdbc_user}"
			password="${jdbc_password}" />
		
		<!-- 類型轉換 -->
		<!-- false:JDBC DECIMAL、NUMERIC類型解析爲Integer,默認方式 -->
	    <!-- true: JDBC DECIMAL、NUMERIC類型解析爲java.math.BigDecimal -->
		<javaTypeResolver>
			<!-- 是否使用bigDecimal, false可自動轉化以下類型(Long, Integer, Short, etc.) -->
			<property name="forceBigDecimals" value="false"/>
		</javaTypeResolver>
		
		<!-- 生成實體類地址 -->	
		<javaModelGenerator targetPackage="com.oop.eksp.user.model"
			targetProject="${project}" >
			<!-- 是否在當前路徑下新加一層schema,eg:fase路徑com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
			<property name="enableSubPackages" value="false"/>
			<!-- 是否針對string類型的字段在set的時候進行trim調用 -->
			<property name="trimStrings" value="true"/>
		</javaModelGenerator>
		
		<!-- 生成mapxml文件 -->
		<sqlMapGenerator targetPackage="com.oop.eksp.user.data"
			targetProject="${project}" >
			<!-- 是否在當前路徑下新加一層schema,eg:fase路徑com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
			<property name="enableSubPackages" value="false" />
		</sqlMapGenerator>
		
		<!-- 生成mapxml對應client,也就是接口dao -->	
		<javaClientGenerator targetPackage="com.oop.eksp.user.data"
			targetProject="${project}" type="XMLMAPPER" >
			<!-- 是否在當前路徑下新加一層schema,eg:fase路徑com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
			<property name="enableSubPackages" value="false" />
		</javaClientGenerator>
		
		<!-- 配置表信息 -->	
		<table schema="${jdbc_user}" tableName="s_user"
			domainObjectName="UserEntity" enableCountByExample="false"
			enableDeleteByExample="false" enableSelectByExample="false"
			enableUpdateByExample="false">
			<!-- schema即爲數據庫名 tableName爲對應的數據庫表 domainObjectName是要生成的實體類 enable*ByExample 
				是否生成 example類   -->
			
			<!-- 忽略列,不生成bean 字段 -->
			<ignoreColumn column="FRED" />
			<!-- 指定列的java數據類型 -->
	      	<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
		</table>

	</context>
</generatorConfiguration>



1、table標籤解析
①屬性
schema即爲數據庫名,tableName爲對應的數據庫表,domainObjectName是要生成的實體類。
若要生成例子可將enableCountByExample等設爲true, 就會生成一個對應domainObjectName的Example類,false則不生成,默認策略是true。
類似的還有enableUpdateByExample、enableDeleteByExample、enableSelectByExample、selectByExampleQueryId屬性。

②子標籤
若要對某些數據庫字段進行操作,可以在table標籤中加入如下標籤
1、忽略某個字段 
<ignoreColumn column="name" />
2、無論數據庫字段是何類型,生成的類屬性都是varchar
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
2、總結
使用Mybatis Generator需要
①兩個jar包——mybatis-generator-core-1.3.2.jar和數據庫jar包
②一個配置文件generator.xml
③執行語句(java -jar F:\xy\jars\mybatis-generator-core-1.3.2.jar -configfile F:\xy\generator.xml -overwrite

3、注意事項
①generator.xml格式:必須是以UTF-8無BOM格式編碼,用notepad++轉換。
②注意數據庫包的可用性,無效的數據庫包轉換會報錯。

附帶上我的init.properties
#Mybatis Generator configuration
project = EKSP
classPath=E:/workplace/EKSP/WebContent/WEB-INF/lib/ojdbc14.jar
jdbc_driver = oracle.jdbc.driver.OracleDriver
jdbc_url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
jdbc_user=INFOGUARDIAN
jdbc_password=info_idap132






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章