1. 程式人生 > 實用技巧 >TCP一些概念(彙總自網路)

TCP一些概念(彙總自網路)

技術標籤:框架mybatis

在寫Mybatis的Mapper對映檔案的時候,我們通常用#{}來獲取傳進來的引數,對於引數的處理其實還是有非常多的規則。

單個引數

對於單個引數,MyBatis不會做引數處理,用#{}取值,裡面括號內不管寫什麼都可以取到值。

//定義介面
 public User selectById(int id);  //通過id查詢

<!--   單個引數查詢-->
    <select id="selectById" resultType="User" >
    select * from JDBC where id =
#{abc} </select>

結果測試:

 @Test
    //查詢
    public void T1() throws Exception {
        InputStream in = Resources.getResourceAsStream("Mybatis.xml");    //載入配置檔案

        SqlSessionFactory SF = new SqlSessionFactoryBuilder().build(in);  //建立sqlSession工廠

        SqlSession s = SF.openSession
(); //建立SqlSession物件 User u = s.selectOne("selectById",1); //呼叫查詢方法 第一個引數是指mapper檔案中id為select的sql語句,第二個引數是指對sql語句傳入的引數 System.out.println(u); //列印查詢到的資料 s.close(); //關閉資源 }

在這裡插入圖片描述

多個引數

MyBatis遇見多個引數會做特殊處理,多個引數會被封裝成一個map。#{}就是從map中獲取指定key的值。而key是param1、param2…param n。

//定義介面
 public User selectByIdAndPassword(int id , String password); //通過id和password查詢

如果此時獲取引數使用#{id}和#{password}是不能成功繫結的。

    <!-- 多個引數查詢-->
    <select id="selectByIdAndPassword" resultType="User">
    select * from JDBC where id = #{id} and password = #{password}
    </select>

執行測試程式碼後會出現下面的錯誤
在這裡插入圖片描述
所以需要將查詢語句中的#{id}和#{password}改為#{param1}和#{param2}

<select id="selectByIdAndPassword" resultType="User">
    select * from JDBC where id = #{param1} and password = #{param2}
 </select>

但是對於多個引數取值還有一種取值方法,使用@Param註解可明確指定封裝map時key的名稱和當前名稱保持一致。此時可以用#{指定的key值}進行取值

public User selectByIdAndPassword(@Param("id") int id ,@Param("password") String password); //通過id和password查詢
 <select id="selectByIdAndPassword" resultType="User">
    select * from JDBC where id = #{id} and password = #{password}
 </select>

在這裡插入圖片描述

如果引數過多,推薦直接傳入物件,然後可以根據#{屬性名}直接取出該屬性的值。
如果傳入的多個引數不是一個物件,此時可以將這些引數封裝成一個map中,然後傳入map即可。

 public User selectByMap(Map map);

<!-- 通過Map查詢-->
    <select id="selectByMap" resultType="User">
    select * from JDBC where id = #{id} and password = #{password}
    </select>
 @Test
    public void T1_1() throws Exception {
        InputStream in = Resources.getResourceAsStream("Mybatis.xml");

        SqlSessionFactory SF = new SqlSessionFactoryBuilder().build(in);

        SqlSession s = SF.openSession();

        MybatisI mybatisI =  s.getMapper(MybatisI.class);

        Map<String,Object> map = new HashMap<String, Object>();
        map.put("id",1);
        map.put("password","111111");

        User u = mybatisI.selectByMap(map);
        System.out.println(u);

        s.close();
    }

在這裡插入圖片描述

特殊場景

public User getUser(@Param(“id”) int id, String name);
取值:id==>#{id} / #{param1} name==>#{param2}

public User getUser(int id,@Param(“e”) User user);
取值:id==>#{param1} name==>#{param2.name} / #{e.name}

public User getUser(List ids);
注意如果是Collection(List、Set)型別或者陣列型別也會特殊處理。也是將list或者陣列封裝到map中。key:Collect型別是(collection),如果是List還可以使用這個key(list);陣列的key是(array)
取值:(取第一個id的值) #{list[0]} / #{collection[0]}