Mybatis框架之常用標籤學習

常用標籤

  1. selectKey標籤:在執行某條sql語句之前或者之後進行的查詢,主要用於自動生成主鍵,語法:<selectKey order="BEFORE/AFTER" resultType="返回值類型" keyProperty="映射的實體的屬性值">
  2. insert標籤:進行插入數據操作。
  3. select標籤:進行數據查詢操作,主要結合其他標籤拼湊查詢。
  4. delete標籤:進行數據刪除操作。
  5. update標籤:進行數據的更新操作。
  6. if標籤:主要用來進行條件查詢或者解決空值插入。具體語法爲:<if test="校驗條件">sql語句</if>
  7. sql標籤:解決重複查詢語句,語法:<sql id="唯一標示">sql語句</sql>
  8. include標籤:引用,主要和sql標籤配合使用。<include refid="sql標籤的id"/>
  9. choose標籤:主要用來條件查詢,類似於switch case語句,用於where語句中。語法:<choose><when test="條件">查詢sql</when><otherwise>查詢sql</otherwise></choose>
  10. set標籤:主要用來進行條件更新。語法:<set><if test="校驗條件">字段=值,</if></set>,最後一個if條件不用加逗號。
  11. foreach標籤:循環使用,主要屬性有:item、index、collection、open、separator、close。item表示集合中每個元素進行迭代時的別名,index表示在迭代過程中每次迭代到的位置,collection表示傳遞的參數集合,open表示該語句以什麼開始,separator表示在每次迭代之間以什麼符號作爲分隔符,close表示該語句以什麼結束,和open對應。
  12. resultMap標籤:當數據表中字段的名稱和實體的名稱不一致時,可以使用此標籤進行映射,則在select標籤中使用resultMap進行查詢。語法:<resultMap type="實體類" id="唯一的標誌"><result column="數據表字段" property="實體屬性"/></resultMap>

常見問題

  1. 插入空值null的處理方式:①使用jdbcType來進行映射轉換;②使用if標籤來進行處理
  2. 查詢中使用map進行查詢時,如果使用id作爲map的key值時,如果使用resultMap進行映射,則map的key值類型和實體的類型保持一致,如果使用的resultType進行映射,則id作爲map的key值,就要看mybatis框架的封裝了,具體可參見以下實例。
  3. 使使 {變量}來進行動態傳入前臺處理的變量值。使用方法:${variable},在map中使用variable作爲key值進行傳遞值。
  4. 別名:在使用map封裝查詢結果時,如果使用別名,則map中只能使用別名進行獲取數值。
  5. 分頁:使用 RowBounds(m,n),其中m表示開始位置,n表示間隔。

實例

標籤使用的配置文件:

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mybatis.commontag">
    <!-- resultMap標籤:當實體類和表字段不對應時,將實體類和表字段一一對應起來,默認爲一致 -->
    <resultMap type="com.mybatis.entity.User" id="userMap">
        <result column="id" property="id"/>  <!-- column:表中字段,property:實體類屬性 -->
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="birthday" property="birthday"/> 
        <result column="address" property="address"/>
        <result column="zipcode" property="zipcode"/>
        <result column="email" property="email"/>
    </resultMap>
    <!-- sql標籤:用來解決重複的sql語句  使用別名解決map中取值爲大寫-->
    <sql id="userField">id "id",username "username",password "password",birthday "birthday",address "address",email "email",zipcode "zipcode"</sql>

    <!-- 使用resultMap進行查詢,使用include來引用sql標籤 -->
    <select id="selectAllUser" resultMap="userMap">
        select <include refid="userField"/> from user_t
    </select>

    <!-- 使用${}傳入sql變量語句 -->
    <select id="selectAllUserByCond" resultType="map" parameterType="map">
        select <include refid="userField"/> from user_t order by ${orderSql}
    </select>

    <!-- 對於非空列,null值插入的兩種處理方法 -->
    <!-- 第一種:進行映射數據類型進行處理,使用jdbcType來進行映射 -->
    <insert id="insertNullValueOne" parameterType="map">
        <selectKey order="BEFORE" resultType="java.lang.Long" keyProperty="id">
            select user_t_seq.nextval from dual
        </selectKey>
        insert into user_t(id,username,password,birthday,email,zipcode,address) 
        values(#{id,jdbcType=INTEGER},#{username,jdbcType=VARCHAR},#{password,jdbcType=VARCHAR},#{birthday,jdbcType=DATE},#{email,jdbcType=VARCHAR},#{zipcode,jdbcType=VARCHAR},#{address,jdbcType=VARCHAR})
    </insert>
    <!-- 第二種: 使用if標籤來進行判斷處理,沒有第一種方便-->
    <insert id="insertNullValueTwo" parameterType="map">
        <selectKey order="BEFORE" resultType="java.lang.Long" keyProperty="id">
            select user_t_seq.nextval from dual
        </selectKey>
        <if test="email!=null">
            insert into user_t(id,username,password,birthday,email,zipcode,address) 
        values(#{id},#{username},#{password},#{birthday},#{email},#{zipcode},#{address})
        </if>
        <if test="email==null">
            insert into user_t(id,username,password,birthday,zipcode,address) 
        values(#{id},#{username},#{password},#{birthday},#{zipcode},#{address})
        </if>
    </insert>

    <!-- choose標籤:類似於switch case語句,用於select -->
    <select id="useChooseToQuery" resultType="map" parameterType="map">
        select <include refid="userField"/> from user_t where 1=1 
            <choose>
                <when test="username != null"> and username like #{username}||'%'</when>
                <when test="password !=null"> and password like #{password}||'%'</when>
                <otherwise> and birthday is null</otherwise>
            </choose>
    </select>

    <!--set標籤:用於條件更新指定的列 -->
    <update id="useSetToUpdate" parameterType="map">
        update user_t
            <set>
                <if test="username != null"> username = #{username},</if>
                <if test="password != null">password = #{password},</if>
                <if test="birthday != null">birthday = #{birthday},</if>
                <if test="address != null">address = #{address},</if>
                <if test="email!=null"> email = #{email},</if>
                <if test="zipcode != null">zipcode = #{zipcode}</if>
            </set>
            <if test="id != null"> where id = #{id}</if>
    </update>
    <!-- foreach標籤:主要是sql中的in的體現 -->
    <select id="useForeachToQuery" resultType="map" parameterType="map">
        select <include refid="userField"/> from user_t where id in 
        <foreach collection="idlist" index="currentIndex" open="(" separator="," close=")" item="eachId">
            #{eachId}
        </foreach>
    </select>
</mapper>

測試使用的文件:

package com.mybatis.entity;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.mybatis.util.SqlSessionFactoryUtil;

/**
 * 測試mybatis的常用標籤
 * @author Administrator
 *
 */
public class TestCommonTag {
private SqlSession session = null;

    @Before
    public void before(){
        SqlSessionFactory factory = SqlSessionFactoryUtil.getSqlSessionFactory();
        if(factory != null){
            session = factory.openSession();
        }
    }

    //測試resultMap以及sql標籤
    @Test
    public void testResultMap(){
        if(session != null){
            System.out.println("------使用List------");
            List<User> lists = session.selectList("mybatis.commontag.selectAllUser");
            for(User user:lists){
                System.out.println("id:" + user.getId() + ",username:" + user.getUsername() + ",password:"+
                        user.getPassword() + ",address:" + user.getAddress() +
                        ",email:" + user.getEmail() + ",zipcode:" + user.getZipcode());
            }
            System.out.println("------使用Map------");
            //在此注意使用id作爲map的key值,且使用resultMap則map的key值和實體保持一致,因此必須使用Long型進行遍歷,否則無法遍歷。
            Map<Long,User> map = session.selectMap("mybatis.commontag.selectAllUser","id");//id作爲map的key值
            Set<Long> keys = map.keySet();
            for(Long key:keys){
                User user = map.get(key);
                System.out.println("id:" + user.getId() + ",username:" + user.getUsername() + ",password:"+
                        user.getPassword() + ",address:" + user.getAddress() +
                        ",email:" + user.getEmail() + ",zipcode:" + user.getZipcode());
            }
        }
    }

    //條件查詢測試,在加入排序條件後,如果使用map則無法按照順序來正確查詢,使用list可以正確進行排序,且使用別名後,只能使用別名進行查詢
    @Test
    public void testConditionQuery(){
        if(session != null){
            //傳遞變量到sql語句中
            System.out.println("------使用${}傳入sql變量語句------");
            Map map = new HashMap();
            map.put("orderSql", "username desc,id desc");
            System.out.println("------使用List------");
            List<Map> lists = session.selectList("mybatis.commontag.selectAllUserByCond",map,new RowBounds(2, 2));//使用分頁,查詢2、3條記錄
            for(Map valueMap:lists){
                System.out.println("id:" + valueMap.get("id") + ",username:" + valueMap.get("username") + ",password:"+
                        valueMap.get("password") + ",address:" + valueMap.get("address") +
                        ",email:" + valueMap.get("email") + ",zipcode:" + valueMap.get("zipcode"));
            }

            System.out.println("------使用Map------");
            //在此注意使用id作爲map的key值,沒有使用resultMap,只使用resultType=map,則Map的key值爲BigDecimal,否則無法遍歷。
            Map resultMap = session.selectMap("mybatis.commontag.selectAllUserByCond",map,"id");//id作爲map的key值
            Set<BigDecimal> keys = resultMap.keySet();
            for(BigDecimal key:keys){
                Map valueMap =  (Map) resultMap.get(key);
                System.out.println("id:" + valueMap.get("id") + ",username:" + valueMap.get("username") + ",password:"+
                        valueMap.get("password") + ",address:" + valueMap.get("address") +
                        ",email:" + valueMap.get("email") + ",zipcode:" + valueMap.get("zipcode"));
            }
        }
    }


    //空值處理的測試:映射處理空值
    @Test
    public void testReflectDealNullValue(){
        Map map = new HashMap();
        map.put("username", "wangwu");
        map.put("password", "wangwu123");
        map.put("address", "上海市黃浦區南京東路");
        map.put("zipcode", "123453");
        if(session != null){
            session.insert("mybatis.commontag.insertNullValueOne",map);
        }
    }
    //空值處理的測試:使用if標籤
    @Test
    public void testIfTagDealNullValue(){
        Map map = new HashMap();
        map.put("username", "wangwu");
        map.put("password", "wangwu123");
        map.put("address", "上海市黃浦區南京東路");
        map.put("zipcode", "123453");
        try {
            map.put("birthday", new SimpleDateFormat("yyyy-MM-dd").parse("1990-04-02"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(session != null){
            session.insert("mybatis.commontag.insertNullValueTwo",map);
        }
    }

    //使用choose標籤動態選擇
    @Test
    public void testUseChooseToQuery(){
        Map map = new HashMap();
        map.put("password", "li");
        if(session != null){
            List<Map> lists = session.selectList("mybatis.commontag.useChooseToQuery",map);
            for(Map valueMap:lists){
                System.out.println("id:" + valueMap.get("id") + ",username:" + valueMap.get("username") + ",password:"+
                        valueMap.get("password") + ",address:" + valueMap.get("address") +
                        ",email:" + valueMap.get("email") + ",zipcode:" + valueMap.get("zipcode"));
            }
        }
    }

    //使用set標籤動態更新
    @Test
    public void testUseSetToUpdate(){
        Map map = new HashMap();
        map.put("id", 23);
        map.put("username", "張三三");
        map.put("password", "zhangsansan123");
        try {
            map.put("birthday", new SimpleDateFormat("yyyy-MM-dd").parse("1993-08-02"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(session != null){
            session.update("mybatis.commontag.useSetToUpdate", map);
        }
    }
    //測試foreach標籤
    @Test
    public void testUseForeachToQuery(){
        Map map = new HashMap();
        List list = new ArrayList();
        list.add(11);
        list.add(21);
        list.add(23);
        list.add(25);
        map.put("idlist", list);
        if(session != null){
            List<Map> lists = session.selectList("mybatis.commontag.useForeachToQuery",map);
            for(Map valueMap:lists){
                System.out.println("id:" + valueMap.get("id") + ",username:" + valueMap.get("username") + ",password:"+
                        valueMap.get("password") + ",address:" + valueMap.get("address") +
                        ",email:" + valueMap.get("email") + ",zipcode:" + valueMap.get("zipcode"));
            }
        }
    }

    @After
    public void after(){
        if(session != null){
            session.commit();//session需要commit 否則無法盡心提交
            session.close();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章