1. 程式人生 > >SqlMapConfig.xml , 輸入對映 ,輸出對映 ,動態sql ,sql片段

SqlMapConfig.xml , 輸入對映 ,輸出對映 ,動態sql ,sql片段

1.SqlMapConfig.xml

   在前面已經簡單的使用過SqlMapConfig.xml中的mapper ,以下將介紹幾個標籤 :

   首先SqlMapConfig是 mybatis的配置檔案:
(1)properties 屬性
將資料庫連線引數單獨的配置在db.properties中,主需要在SqlMapConfig.xml中載入db.properties的屬性值,在SqlMapConfig.xml中不需要配置對資料庫連線引數的硬編碼。
        原因是:方便對引數進行統一的管理,其他xml可以載入引用該db.properties

      比如 :
     db.properties 

oracle.driver=oracle.jdbc.OracleDriver
oracle.url=jdbc:oracle:thin:@localhost:1521:xe
oracle.name=hr
oracle.pass=yuan
   

    properties屬性 :

<properties resource="db.properties"></properties>

   使用 :
<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${oracle.driver}" />
				<property name="url" value="${oracle.url}" />
				<property name="username" value="${oracle.name}" />
				<property name="password" value="${oracle.pass}" />
				<!-- 	<property name="driver" value="oracle.jdbc.OracleDriver" />
				<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
				<property name="username" value="hr" />
				<property name="password" value="yuan" /> -->
			</dataSource>
		</environment>
	</environments>

               注意:MyBatis將按照下面順序來載入屬性:
          1) 在properteis元素體內定義的屬性首先被讀取;
          2) 然後會讀取properties元素中resource或url載入的屬性,它會覆蓋已讀取的同名屬性;
           3) 最後讀取parameerType傳遞的屬性,它會覆蓋已讀取的同名屬性;
 因此,通過paramterType傳遞的屬性具有最高優先順序,resource或url載入的屬性次之,最低優先順序的是properties元素體內定義的屬性;
 
 建議:不要在properties元素體內新增任何屬性值,只將屬性值定義在properties檔案中,在properties中檔案定義屬性名一定的特殊性,如:xxx.xxxx

   (2) setting 全域性引數配置
mybatis框架在執行時可以調整執行引數,需要得時候設定,不需要的時候不要亂設定;
    使用 :

<settings><settings>

   (3)typeAliases 別名
 在mapper.xml中,定義了很多的statement,statement需要parameterType制定的輸入引數型別,和resultType制定的輸出結果對映型別;
 如果在指定型別時輸入型別全路徑,不方便開發,可以針對paramterType或resultType指定的型別定義一些別名,在mapper.xml中通別名定義,方便開發;
使用:
                                        <typeAliases>
				           單挑定義
				           <typeAlias type="包名" alias=""/>
						   多條定義,別名就是類名
						   <package  name="包名"/>
				       </typeAliases>
			

       示列 :
  <typeAliases>
       <typeAlias type="cn.labelnet.pojo.Client" alias="client"/>
       <typeAlias type="cn.labelnet.pojo.Operation" alias="operation"/>
    
    </typeAliases>

      (4)typeHandlers 型別處理器
   mybatis中通過typeHandlers完成jdbc型別和java型別轉換;通常情況下,mybatis提供的型別處理器滿足日常需要,不需要自定義;

       5)mappers (對映器)
    1)通過resource載入 : <mapper resource=" " />
    2)通過mapper介面載入對映檔案 :<mapper class=""/> ,規範:需要mapper介面類名和mapper.xml
對映檔名稱保持一致,且在一個目錄中,使用的是mapper代理方向;
    3)通過package 批量載入mapper ,指定mapper介面包名,mybatis自動掃描包下的所有mapper介面進行載入;

	<mappers>
	    <package name="包名"/>
	    <!-- mapper.xml -->
	    <mapper resource="mapper/ClientMapper.xml"/>
	    <mapper resource="mapper/OperationMapper.xml"/>
	</mappers>

2.輸入對映 (注意 : Mapper.xml檔案 的statement中sql語句不準出現 分號 ;)

     通過paramteType指定的輸入引數型別,型別可以是簡單型別,hashmap,pojo包裝型別;
 (1)傳遞pojo的包裝物件
完成綜合查詢(關聯查詢)的時候,建議使用自定義的包裝型別pojo ,將複雜的查詢條件包裝為pojo型別;
 
(2)例項 :多條件查詢實現

 1)Mapper.xml實現 :

 <select id="selectOperationIfos" parameterType="cn.labelnet.pojo.OperationQueryVo1" resultType="cn.labelnet.pojo.OperationCustom">
       
        select * from f_operation where  f_operation.client_id=#{c.id} and f_operation.legal_person_name='${name}'
    
    </select>
 
 2)介面實現
//多條件查詢
	public OperationCustom selectOperationIfos(OperationQueryVo1 oa);
 

  3)包裝類實現

/**
 * 自定義包裝型別,查詢條件
 * 描述: TODO
 * 作者 :原明卓
 * 時間 :2015年12月22日 下午3:02:20
 * 版本 :1.0
 */
public class OperationQueryVO {
	

	//經營資訊的條件
    private OperationCustom operation;

	public Operation getOperation() {
		return operation;
	}

	public void setOperation(OperationCustom operation) {
		this.operation = operation;
	}
    
    

}

  4)經營資訊 operation pojo實現
package cn.labelnet.pojo;

import java.util.Date;

/**
 * 經營資訊
 * 
 * 作者 :原明卓
 * 時間 :2015年12月22日 上午9:22:57
 * 包名 :cn.labelnet.pojo
 * 描述 :TODO
 */
public class Operation {
	//資產編號
	private Integer id;
	//使用者編號
	private Integer client_id;
	//資產資訊描述
	private String operate_infomation_describe;
	//持股比例
	private Integer possess_sharholding;
	//經營地址
	private String operate_address;
	//年收入
	private String year_avg_income;
	//開始經營日期
	private Date begin_operation_time;
	//員工總數
	private Integer employees_amount;
	//法人姓名
	private String legal_person_name;
	//法人證件號碼
	private String legal_person_crd_number;
	//經營證件號碼
	private String operate_crd_number;
	//更新時間
	private Date update_time;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Integer getClient_id() {
		return client_id;
	}
	public void setClient_id(Integer client_id) {
		this.client_id = client_id;
	}
	public String getOperate_infomation_describe() {
		return operate_infomation_describe;
	}
	public void setOperate_infomation_describe(String operate_infomation_describe) {
		this.operate_infomation_describe = operate_infomation_describe;
	}
	public Integer getPossess_sharholding() {
		return possess_sharholding;
	}
	public void setPossess_sharholding(Integer possess_sharholding) {
		this.possess_sharholding = possess_sharholding;
	}
	public String getOperate_address() {
		return operate_address;
	}
	public void setOperate_address(String operate_address) {
		this.operate_address = operate_address;
	}
	public String getYear_avg_income() {
		return year_avg_income;
	}
	public void setYear_avg_income(String year_avg_income) {
		this.year_avg_income = year_avg_income;
	}
	public Date getBegin_operation_time() {
		return begin_operation_time;
	}
	public void setBegin_operation_time(Date begin_operation_time) {
		this.begin_operation_time = begin_operation_time;
	}
	public Integer getEmployees_amount() {
		return employees_amount;
	}
	public void setEmployees_amount(Integer employees_amount) {
		this.employees_amount = employees_amount;
	}
	public String getLegal_person_name() {
		return legal_person_name;
	}
	public void setLegal_person_name(String legal_person_name) {
		this.legal_person_name = legal_person_name;
	}
	public String getLegal_person_crd_number() {
		return legal_person_crd_number;
	}
	public void setLegal_person_crd_number(String legal_person_crd_number) {
		this.legal_person_crd_number = legal_person_crd_number;
	}
	public String getOperate_crd_number() {
		return operate_crd_number;
	}
	public void setOperate_crd_number(String operate_crd_number) {
		this.operate_crd_number = operate_crd_number;
	}
	public Date getUpdate_time() {
		return update_time;
	}
	public void setUpdate_time(Date update_time) {
		this.update_time = update_time;
	}
	@Override
	public String toString() {
		return "Operation [id=" + id + ", client_id=" + client_id
				+ ", operate_infomation_describe="
				+ operate_infomation_describe + ", possess_sharholding="
				+ possess_sharholding + ", operate_address=" + operate_address
				+ ", year_avg_income=" + year_avg_income
				+ ", begin_operation_time=" + begin_operation_time
				+ ", employees_amount=" + employees_amount
				+ ", legal_person_name=" + legal_person_name
				+ ", legal_person_crd_number=" + legal_person_crd_number
				+ ", operate_crd_number=" + operate_crd_number
				+ ", update_time=" + update_time + "]";
	}
}
   5)經營資訊operation 擴充套件類實現
/**
 * 經營資訊拓展類
 * 描述: TODO
 * 作者 :原明卓
 * 時間 :2015年12月22日 下午3:01:17
 * 版本 :1.0
 */
public class OperationCustom extends Operation{
	
	//拓展經營資訊pojo
	   //聯絡方式
	
	  private String username;
	
    public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	private String contact_mode;
    public String getContact_mode() {
		return contact_mode;
	}
	public void setContact_mode(String contact_mode) {
		this.contact_mode = contact_mode;
	}
	public String getUrgency_contact_mode() {
		return urgency_contact_mode;
	}
	public void setUrgency_contact_mode(String urgency_contact_mode) {
		this.urgency_contact_mode = urgency_contact_mode;
	}
	//緊急聯絡方式
    private String urgency_contact_mode;
	
	
}

  6)測試
@Test
	public void testselectOperationIfos(){
		SqlSession os = sqlSessionFactory.openSession();
		OperationMapper om = os.getMapper(OperationMapper.class);

		OperationQueryVo1 oa = new OperationQueryVo1();
		oa.setName("吳迪");
		Client client=new Client();
		client.setId(14);
		oa.setC(client);

		OperationCustom oc = om.selectOperationIfos(oa);
		
		
		System.out.println(oc);
	}

    輸入對映 ,主要使用了包裝類,有時候查詢條件多個引數,需要使用一個包裝類,作為輸入對映物件;

 

3.輸出對映

   (1)resultType
1)使用resultType進行對映,只有查詢出來的列表和pojo中的屬性名一致,該列才可以對映成功。
2)如果查詢出來的列表和pojo中的屬性名全部不一致,沒有建立pojo物件;
        3)只有查詢出來的列名和屬性名一個一致,就會建立pojo物件; 
4)查詢輸出的結果集只有一行且一列,可以使用簡單型別進行輸出對映;
5)不管是輸出的pojo單個物件還是一個列表(list中包括pojo),在mapper.xml中resslType指定的型別時一致的。
生成的動態代理物件中的根據  比如 :pojo : Fclient ,進行擴充套件類 FclientCustom;
 
  ( 2)resultMap
         如果查詢出來的列名和pojo的屬性名不一致,通過定義一個resultmap定義列名與屬性名之間的對映;
          1)定義resultmap 
  <!-- 定義resultMap : type:resultMap最終 對映的java物件型別,可以使用別名、
  id :對resultMap的 唯一標識 -->
   <resultMap type="operation" id="openatoinResultMap">
     
 <!--      column :查詢出來的列名
      property : type指定的pojo型別的屬性名
      最終resultMap對column和property作一個對映關係(對應關係) -->
     <!--  唯一列的標識 -->
      <id column="id_" property="id"/>
<!--       對普通列的標識 -->
      <result column="client_id_" property="client_id"/>
   </resultMap>


          2)使用resultmap作為statement的輸出對映;

<!-- 	測試Reusultmap ,如果resultmap在其他mapper,則加上 mapper的名稱空間  -->
	 <select id="selectOperationIfosResultMap" parameterType="cn.labelnet.pojo.OperationQueryVo1" resultMap="openatoinResultMap">
       
        select id id_ , client_id client_id_ from f_operation where  f_operation.legal_person_name='${name}'
    
    </select>

  綜合查詢 :  

   比如進行下面查詢 :

select id id_ ,client_id client_id_ from f_operation where  f_operation.legal_person_name='吳迪';


         

    1)實現 介面

	//多條件查詢
	public Operation selectOperationIfosResultMap(OperationQueryVo1 oa);
   2)resultMap 配置如上所示

    
   3)測試

	@Test
	public void testselectOperationIfosResultmap(){
		SqlSession os = sqlSessionFactory.openSession();
		OperationMapper om = os.getMapper(OperationMapper.class);

		OperationQueryVo1 oa = new OperationQueryVo1();
		oa.setName("吳迪");
		Client client=new Client();
		client.setId(14);
		oa.setC(client);

		 Operation oc = om.selectOperationIfosResultMap(oa);
		
		System.out.println(oc);
	}
	

4.動態Sql

   之間在statement中實現 :mybatis核心 對sql語句進行靈活的操作,通過表示式進行判斷,對sql進行靈活的拼接,組裝;

 綜合查詢,對查詢條件進行判斷,後進行拼接:
 

  <select>
			     select * from user
				 <where>
				   <if test="user!=null">
						<if test="user.id!=null and user.id!=''">
						   and user.id=#{user.id}
						</if>
						<if test="user.name!=null and user.name!=''">
						   and user.name=#{user.name}
						</if>
						....
					</if>
				 
				 </where>
			    
			   </select>


5.Sql片段

   定義Sql片段 ,可以重複使用條件,將上面的動態sql判斷程式碼塊抽取出來,組成一個sql片段,為了可重用性;id為sql片段的唯一標示,單表定義; 不要包含where ,比如下面的mapper檔案 :
 

<mapper>
			   <sql id="query_where">
			        <if test="user!=null">
						<if test="user.id!=null and user.id!=''">
						   and user.id=#{user.id}
						</if>
						<if test="user.name!=null and user.name!=''">
						   and user.name=#{user.name}
						</if>
						....
					</if>
			   </sql>
			   
			   
			   <select>
			      select * from user
				 <where>
	                   <include refid="query_where" />
					   ...還可以引用其他的sql片段
				 </where>			    
			   </select>
			   
			 </mapper>

6.foreach 

向sql傳遞屬性或list , mybatis使用foreach解析;傳入多個id 時,比如 : where id=1 or id=1 or id=2 或 id in(1,20,23)
  
  <sql id="query_where">
			        <if test="user!=null">
						<if test="user.id!=null and user.id!=''">
						   and user.id=#{user.id}
						</if>
						<if test="user.name!=null and user.name!=''">
						   and user.name=#{user.name}
						</if>
						foreach 遍歷傳入集合ids
						sql條件 : and (id=1 or id=10 or id=12)
						<foreach collection="ids" item="item_id" open="and {" close="}" separator="or">
						   拼接sql 語句 :and (id=1 or id=10 or id=12)
						   id=#{item_id}
						</foreach>
						....
					</if>
			   </sql>

 7.Demo免積分下載

相關推薦

Mybatis學習筆記(五) —— Mapper.xml(輸入對映輸出對映

一、parameterType(輸入型別) 1.1 傳遞簡單型別 <!-- 根據使用者id查詢使用者 --> <select id="queryUserById" parameterType="int" resultType="cn.itc

mybatis基礎系列(二)——基礎語法、別名、輸入對映輸出對映

增刪改查 <mapper>根節點及其子節點 mybatis框架需要讀取對映檔案建立會話工廠,對映檔案是以<mapper>作為根節點,在根節點中支援9個元素,分別為insert、update、delete、select(增刪改查);cache、cache-ref、resultMap、

MyBatis的學習總結三——輸入對映輸出對映以及多表關聯查詢

關於MyBatis的輸入對映和輸出對映,可輸入的型別很多,輸出型別亦是如此。如圖所示: 一、輸入型別是通過引數parameterType來設定的,引數型別有基本資料型別、包裝型別pojo、Map 基礎型別(String,int,long,double...) pojo型別

編寫程式可一直接收鍵盤字元輸入小寫字元輸出大寫字元;輸入大寫字元輸出小寫字元;輸入數字不輸出

#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> int main() { char str1[] = "abcdefghijklmnopwrstuvwxyz"; char str2[

程式設計輸入一個10進位制正整數然後輸出它所對應的八進位制數。

方法一 import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); whil

linux shell介面變成灰色輸入左移動輸出[D^

原因是 是使用者下面使用的是 /bin/dash 修改方法: ls -l `which sh` 輸出:/bin/sh -> dash sudo dpkg-reconfigure dash #Select "no" when you're asked ls -l `whi

java語言中輸入A,B輸出A+B的值

問題如下: 計算一對A、B的和或者計算多對A、B值的和; 輸入格式: 輸入的第一行包括兩個數(即A,B對,中間用空格隔開),也可以在第一行輸入多個A、B對; 輸出格式: 對於輸出的A、B中的和要與輸入的A、B對一一對應,並且A+B獨自佔一行; 1.每次只輸入一對A、B時,

Mybatis之輸入對映輸出對映

輸入型別(parameterType) 傳遞簡單型別(參考Mybatis入門程式) 傳遞POJO物件(Mybatis使用Ognl表示式解析物件欄位的值,#{}佔位符與拼接符 ${}括號內的值為POJO屬性名稱) 傳遞POJO包裝物件 開發中通過

Spring+SpringMVC+MyBatis深入學習及搭建(四)——MyBatis輸入對映輸出對映

1. 輸入對映 通過parameterType指定輸入引數的型別,型別可以是簡單型別、hashmap、pojo的包裝型別。 1.1 #{}與${} #{}實現的是向prepareStatement中的預處理語句設定引數值,sql語句中#{}表示一個佔位符即? <select id="findUse

編寫函式輸入一個十六進位制數輸出相應的十進位制數。

#include<stdio.h> #include<string.h> #include<math.h> int output(char str[]) {     int l=strlen(str);     int i;     in

MyBatis輸入對映輸出對映動態SQL、關聯關係、Spring整合加強筆記

1.  計劃 1.        輸入對映 2.        輸出對映 3.        動態SQL 4.        關聯關係 5.        Spring整合MyBatis 2.  輸入對映 2.1.1. 輸入對映-包裝pojo 我們假設建立一個身份證資

在Excel2003中用A表示第1列B表示第2列。。。Z表示第26列AA表示第27列AB表示第28列。。。以此類推。請寫出一個函式輸入用字母表示的列號編碼輸出它是第幾列

這道題其實就是26進位制字串轉十進位制的題,由於A到Z在ASCii中是連續的 補充知識點: 在ASCII碼中,我們要記住幾個關鍵的字元! 0:48 A:65 a:97 (1)數字在前,大寫字母其後,最後是小寫字母。 (2)小寫字母和大寫字母差32。 下面是簡單的模擬過程

XAF 框架中自定義參數動作(Action)輸入參數的控件可定義用於選擇組織及項目

示例 app frame tro href express documents 定義 ron XAF 框架中,如何生成一個自定義參數動作(Action),輸入參數的控件可定義? 參考文檔:https://documentation.devexpress.com/eXpres

讀取csv檔案1min k線輸出到csv檔案中計算5s10s20s移動平均值

參考: C字串轉換為int,float https://blog.csdn.net/li6727975/article/details/42875641 結構體 http://www.runoob.com/cprogramming/c-structures.htm

在Chrome與火狐中輸入框input類型為number時如何去除掉的自帶的上下默認箭頭

顯示 image 默認 webkit put 如何 ber textfield app 如何移除input=‘number‘時瀏覽器自帶的上下箭頭: CSS樣式: /* 去除input[type=number]瀏覽器默認的icon顯示 */

SqlMapConfig.xml 輸入對映 輸出對映 動態sql sql片段

1.SqlMapConfig.xml    在前面已經簡單的使用過SqlMapConfig.xml中的mapper ,以下將介紹幾個標籤 :    首先SqlMapConfig是 mybatis的配置檔案:(1)properties 屬性將資料庫連線引數單獨的配置在db.p

mybatis 多表關聯查詢時如果使用resultType作為輸出對映估計會出現重複資料

mybatis 多表關聯查詢時,一般建議還是使用把需要關聯的表的pojo新增到主表對應的pojo中作為它的屬性,這樣在mapper.xml檔案中可以使用assacition(一對一查詢),或者colletion(一對多查詢)來使用resultMap作為輸出對映。 不過最近我

在web.xml中配置servlet的URL對映瀏覽器訪問出錯

在一些servlet教程中,給出的servlet的URL對映配置方式是,在web.xml中新增servlet元素和servlet-mapping元素: <servlet> <servlet-name>ServletDemo01&l

MyBatis框架的學習(四)——Mapper.xml檔案中的輸入輸出對映以及動態sql

前面對MyBatis框架的學習中,我們對Mapper.xml對映檔案多少有些瞭解。本文將對Mapper.xml對映檔案作更加細緻的梳理,首先從Mapper.xml檔案中的輸入和輸出對映開始。本文案例程式碼的編寫是建立在前文MyBatis框架的學習(三)——Dao

Mybatis-Mapper.xml輸入輸出對映

在Mybatis中,Mapper.xml主要負責對資料庫的具體操作,即增、刪、改、查等相關操作, 對於mapper.xml,我們需要掌握一些常用的標籤,下面做出介紹。 首先,先對此次講解資料庫表做一個說明,資料庫表字段為id、username、sex、birthday、ad