Mybatis 實用篇(三)參數處理

來源:互聯網
上載者:User

標籤:使用   mybatis   一個   工作   interface   拼接   @param   取出   資料庫   

Mybatis 實用篇(三)參數處理

sql 語句中的參數 parameterType 可以省略不寫。

一、參數封裝1.1 單個參數處理
public interface UserMapper {    User getUser(int id);}

sql 中 #{} 的值可以隨意,mybatis 不做任何處理,eg:

<select id="getUser" parameterType="int" resultType="User">    select * from user where id=#{xxx};</select>
1.2 多個參數處理

多個參數 mybatis 封裝成 Map,預設參數的 key 為 param1, param2...,也可以使用 @Param("id") 指定 key 的值

User getUser(@Param("id") int id, String name);

sql 可以有如下寫法:

<select id="getUser" resultType="User">    <!--select * from user where id=#{0} and name=#{1};-->    <!--select * from user where id=#{param1} and name=#{param2};-->    <!--select * from user where id=#{0} and name=#{param2};-->    select * from user where id=#{id} and name=#{param2};</select>
1.3 Java Bean
User getUser(User user);

sql 可以有如下寫法:

<select id="getUser" resultType="User">    select * from user where id=#{id} and name=#{name};</select>
1.4 Map
User getUser(User user);

sql 可以有如下寫法:

<select id="getUser" resultType="User">    select * from user where id=#{id} and name=#{name};</select>

思考:

User getUser(@Param("id") int id, String name);id ==> #{id/param1/0}   name ==> #{param2/1}User getUser(int id, @Param("user") User user);id ==> #{id/param1/0}   name ==> #{param2.name/user.name}# Collection ==> list, Array ==> array. eg: 取出 list 中的第一個值User getUser(List<User> users);id ==> #{list[0]}
二、#{} 和 ${} 區別

#{} 先行編譯,而 ${} 僅進行字串拼接。

實際工作中,盡量使用 #{} ,特殊場合需要使用 ${},如:

select * from ${tablename}
三、#{} 參數

mybatis 值為 null 時預設對應資料庫中的 TYPES.OHTER,可以修改全域的配置:

  • {email, javaType=NULL}

每天用心記錄一點點。內容也許不重要,但習慣很重要!

Mybatis 實用篇(三)參數處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.