Mybatis使用記錄

Mybatis使用記錄

mybatis是j2ee中一個重要的orm,mybatis有自動化生成工具,更加方便使用

繼承

mybatis支持繼承,其中Mapper映射文件會自動合併,如下,兩個xml中列出的方法是可以映射到同一個TestDAO.java中的,這樣可以方便的將自定義的sql放在Ex.xml中,自動生成的放在第一個xml中,便於數據庫變化後自動生成
TestMapper.xml

<mapper namespace="com.rjw.j2ee.dal.dao.TestDAO" >
……
</mapper>

TestExMapper.xml

<mapper namespace="com.rjw.j2ee.dal.dao.TestDAO" >
……
</mapper>

數據庫字段最好加上表名,方便Join查詢,同時儘量不要使用sql的關鍵字作爲表名。

mybatis參數

mybatis可以通過三種方式傳入參數,#{0}佔位符,#{param1}佔位符,@Param註解標記參數。動態SQL中test語句可以解析param1和Param註解。使用前兩種佔位符,需要設置 parameterType=”map”

mybatis嵌套

可以使用association嵌套,分爲兩種,一種子查詢,一種聯合查詢,子查詢時在ResultMap中配置select,其中select對應的語句有配置相應的ResultMap:

<association property="property" column="column" javaType="com.rjw.j2ee.test.TestModel" select="ccom.rjw.j2ee.test.dal.dao.TestDao.selectByPrimaryKey"/>

聯合查詢時,在ResultMap中嵌套ResultMap

<resultMap id="blogResult" type="Blog">
  <id property="id" column="blog_id" />
  <result property="title" column="blog_title"/>
  <association property="author" column="blog_author_id" javaType="Author" resultMap="authorResult"/>
</resultMap>

<resultMap id="authorResult" type="Author">
  <id property="id" column="author_id"/>
  <result property="username" column="author_username"/>
  <result property="password" column="author_password"/>
  <result property="email" column="author_email"/>
  <result property="bio" column="author_bio"/>
</resultMap>

<select id="selectBlog" resultMap="blogResult">
  select
    B.id            as blog_id,
    B.title         as blog_title,
    B.author_id     as blog_author_id,
    A.id            as author_id,
    A.username      as author_username,
    A.password      as author_password,
    A.email         as author_email,
    A.bio           as author_bio
  from Blog B left outer join Author A on B.author_id = A.id
  where B.id = #{id}
</select>

多記錄插入,其中foreach中collection的值只有list和collection

<insert id="selectPostIn" resultType="domain.blog.Post">
  insert into employees
    (
            <include refid="Base_Column_List" />
    )
values
<trim suffix="" suffixOverrides=",">
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
      uuid, 
      #{item.id},
      #{item.name},
      #{item.value}
  </foreach>
 </trim>
</insert>

插入時主鍵的處理

批量插入時使用selectKey時所有記錄的主鍵都是一樣的,故下面方式會報錯主鍵重複錯

<insert id="selectPostIn" resultType="domain.blog.Post">
<selectKey keyProperty="key_uid" resultType="String" order="BEFORE">
    select uuid()
  </selectKey>
  insert into employees
    (
            <include refid="Base_Column_List" />
    )
values
<trim suffix="" suffixOverrides=",">
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
      #{key_uid}, 
      #{item.id},
      #{item.name},
      #{item.value}
  </foreach>
 </trim>
</insert>

mybatis簡單分頁

直接在DAO.java的接口中聲明重載方法,加入參數RowBounds即可

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