1. 程式人生 > >Mybatis之輸入輸出對映(共三種類型)

Mybatis之輸入輸出對映(共三種類型)

一、輸入parameterType輸出resultType型別(resultType:列名和pojo中的屬性名要一致

Mybatis使用ognl表示式解析物件欄位的值,#{}或者${}括號中的值為pojo屬性名稱,其中,#{}:佔位符號,相對於?,${}:sql拼接符號,相對於String

select * from user where name = #{name};   會被動態解析為    select * from user where name = ?; 

select * from user where name = ${name}; 當我們傳遞引數"mark"時,會被解析 select * from user where name = "mark"; 

<!-- 1、resultType:如果要返回資料集合,只需設定為每一個元素的資料型別
		 2、 包裝的pojo取值通過 "."來獲取
	-->
	<select id="getUserByQueryVo" parameterType="queryvo" resultType="com.mark.pojo.User">
		<!-- SELECT * FROM USER WHERE username LIKE #{name} -->
		SELECT * FROM USER WHERE username LIKE '%${user.username}%'
	</select>

  二、輸出resultMap(列名和pojo中的屬性名不一致) 

resultMap包含元素

<!--column不做限制,可以為任意表的欄位,而property須為type 定義的pojo屬性-->
<resultMap id="唯一的標識" type="對映的pojo物件">
  <id column="表的主鍵欄位,或者可以為查詢語句中的別名欄位" jdbcType="欄位型別" property="對映pojo物件的主鍵屬性" />
  <result column="表的一個欄位(可以為任意表的一個欄位)" jdbcType="欄位型別" property="對映到pojo物件的一個屬性(須為type定義的pojo物件中的一個屬性)"/>
  
 <!-- 一對一關聯-->
 <association property="pojo的一個物件屬性" javaType="pojo關聯的pojo物件">
    <id column="關聯pojo物件對應表的主鍵欄位" jdbcType="欄位型別" property="關聯pojo物件的主席屬性"/>
    <result  column="任意表的欄位" jdbcType="欄位型別" property="關聯pojo物件的屬性"/>
  </association>

  <!-- 一對多關聯-->
  <!-- 集合中的property須為ofType定義的pojo物件的屬性-->
  <collection property="pojo的集合屬性" ofType="集合中的pojo物件">
    <id column="集合中pojo物件對應的表的主鍵欄位" jdbcType="欄位型別" property="集合中pojo物件的主鍵屬性" />
    <result column="可以為任意表的欄位" jdbcType="欄位型別" property="集合中的pojo物件的屬性" />  
  </collection>

</resultMap>

如果collection標籤是使用巢狀查詢,<collection>標籤中的column:要傳遞給select查詢語句的引數,如果傳遞多個引數,格式為column=  {引數名1=表字段1,引數名2=表字段2} ;格式如下

 <collection column="傳遞給巢狀查詢語句的欄位引數" property="pojo物件中集合屬性" ofType="集合屬性中的pojo物件" select="巢狀的查詢語句" > 
 </collection>

 userMapper例項

<mapper namespace="com.mark.mapper.userMapper">
   
    <!-- 
    定義resultMap
    type:resultMap最終對映的java物件型別,可以使用別名
    id:對resultMap的唯一標識
     -->
    <resultMap type="User" id="userResultMap">
        <!-- 
        column:查詢出來的列名
        property:type指定的pojo型別中的屬性名
        最終resultMap對column和property作一個對映關係(對應關係)
         -->
        <!-- 主鍵用id -->
        <id column="id" property="id"/>
        <!-- 普通欄位用result -->
        <!-- 單表查詢可以不寫全,關聯查詢必須寫全所有欄位 -->
        <result column="user_name" property="username"/>
    </resultMap>
    
        <!-- 這裡的resultMap要和<resultMap type="User" id="userResultMap">id一致 -->
        <select id="findUserByResultMap" parameterType="com.mark.po.UserQueryVo" resultMap="userResultMap">
        SELECT id, user_name FROM USER WHERE user.username=#{userCustom.username} 
    </select>
    
</mapper>