1. 程式人生 > >mybatis的XML對映檔案中的函式-mybatis(1)

mybatis的XML對映檔案中的函式-mybatis(1)

前言

由mybatis的逆向程式碼生成器生成的6個基本函式在日常開發中是有些力不從心的,我們可以寫寫自定義函式,去完成一些複雜的操作。

正文

繼續以之前建立的springboot專案為基礎,來學習mybatis的xml對映檔案的寫法,主要寫一下我用到比較多的一些元素。具體可以看官網
專案建立文章配置springboot和mybatis逆向生成器

常用的頂級元素

  • ResultMap 定義了資料庫的列和實體屬性的對映關係
  • sql 定義要重複應用的程式碼
  • select查詢函式
  • delete刪除函式
  • insert插入函式
  • update
    更新函式

ResultMap

一個具體的程式碼如下

<resultMap id="BaseResultMap" type="com.nick.hello.entity.User" >
    <id column="id" property="id" jdbcType="VARCHAR" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
  </resultMap>

其含義是:java中的com.nick.hello.entity.User的屬性id,name,password分別自動對映到資料庫中的列名 id,name,password.這個在我們資料庫列名與實體屬性不是完全對應時很有用。

sql

sql中定義的程式碼可以重複使用

  <sql id="Base_Column_List" >
    id, name, password
  </sql>

指定資料庫中的所有列名。要引用時只需要新增refid="id"

select

一個簡單的select函式

<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=VARCHAR}
  </select>

這個函式的作用是通過id來查詢記錄。

  • id不能省略,可以被用來代表這個語句,對應Mapper中的函式名
  • ResultMap定義結果怎麼對映
  • parameterType是傳入引數型別
  • #{}就相當於jdbc中的?
select id, name,password from user where id='id'

insert

類似,例項程式碼

<insert id="insert" parameterType="com.nick.hello.entity.User" >
    insert into user (id, name, password
      )
    values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
      )
  </insert>

引數型別是我們自己定義的User

delete

  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    delete from user
    where id = #{id,jdbcType=VARCHAR}
  </delete>

刪除語句,通過id刪除記錄

update

  <update id="updateByPrimaryKey" parameterType="com.nick.hello.entity.User" >
    update user
    set name = #{name,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR}
    where id = #{id,jdbcType=VARCHAR}
  </update>

這些是簡單的xml對映函式,mybatis還支援更加強大的動態sql語句。xml對映函式簡潔但是功能強大,也許幾行對映函式在業務邏輯中要實現的話就需要幾倍的程式碼量了。