MyBatis學習二:mapper.xml屬性

XXMapper.xml文件
1、id:標識映射文件中的sql;

將sql語句封裝到mapped statement對象中,所以將id稱爲statement的id。

2、parameterType:指定輸入參數類型
3、parameterMap:同parameterType,舊版本
4、resultType:指定sql輸出結果所映射的java對象類型;

select指定resultType,表示將單條記錄映射成的java對象。使用resultType進行輸出映射,只有查詢出來的列名和pojo中的屬性名一致,該列纔可映射成功。

5、resultMap:用於高級輸出結果映射。

使用方法:定義resultMap,使用resultMap作爲statement的輸出映射類型。

<resultMap type=”user” id=”userResultMap”>
	<!—id表示查詢結果集中唯一標識
column:查詢出來的列名
property:type指定的pojo類型中的屬性名
最終resultMap對column和property作一個映射關係(對應關係) -->
<id column=”id_” property=”id”/>
<!—result:對普通名映射定義  最終resultMap對column和property作一個映射關係(對應關係) -->
<result column=”username_” property=”username”/>
</resultMap>

<select id=”findUserByResultMap” parameterType=”int” resultMap=”userResultMap”>
	SELECT id id_, username username_ FROM USER WHERE id=#{value}
</select>

6、#{}表示一個佔位符

#{id}其中的id表示接受輸入的參數,參數名稱是id;如果輸出參數是簡單類型,#{}中的參數名可以任意,可以是value或其他名稱。

如果接受pojo對象值,通過OGNL讀取對象中的屬性值,通過屬性.屬性.屬性的方法獲取對象屬性值。

<select  id=”findUserById”  parameterType=”int”  resultType=”cn.itcast.mybatis.po.User”>
	SELECT * FROM USER WHERE id = #{id}
</select>

<sql id="Base_Column_List" >
    ID, DEPT_NAME, DEPT_NO, FID, WEIGHT, CREATE_DATE
  </sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" 
parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from SYS_MAN_DEPARTMENT
    where ID = #{id,jdbcType=VARCHAR}
  </select>
7、${}表示一個拼接符

將接受到的內容不加任何修飾拼接在sql中;但是會引起sql注入,不建議使用

${value}接受輸入參數的內容,如果傳入類型是簡單類型,${}中只能使用value;如果接受pojo對象值,通過OGNL讀取讀取對象中的屬性值,通過屬性.屬性.屬性的方法獲取對象屬性值。

模糊查詢:

<select  id=”findUserByName”  parameterType=”java.lang.String”
  resultType=”cn.itcast.mybatis.po.User”>
	SELECT * FROM USER WHERE username LIKE ‘%${value}%’
</select>

8、關於主鍵

A)自增主鍵:主鍵id如果是自增的,則不設置,即使設置了也沒效果。

通過mysql函數獲取到剛插入記錄的自增主鍵:LAST_INSERT_ID(),是insert之後調用此函數。

B)非自增主鍵:使用mysql的uuid()函數生成主鍵,需要修改表中id字段類型爲String,長度設置爲35位。執行思路:先通過uuid()查詢到主鍵,將主鍵插入到sql語句中。

C)通過oracle的序列生成主鍵:

根據id更新用戶:

<update  id=”updateUser”  parameterType=”cn.itcast.po.user”>
	update user set username=#{username}, birthday=#{ birthday }, address=#{address} where id=#{id}
</update>






發佈了276 篇原創文章 · 獲贊 2 · 訪問量 48萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章