Mybatis (ParameterType) 如何传递多个不同类型的参数
生活随笔
收集整理的這篇文章主要介紹了
Mybatis (ParameterType) 如何传递多个不同类型的参数
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
問題
當在寫查詢語句的時候需要傳入多個參數(shù)的時候該怎么辦呢?
方法一:不需要寫parameterType參數(shù)
//傳參 public List<XXXBean> getXXXBeanList(String xxId, String xxCode); // sql語句 <select id="getXXXBeanList" resultType="XXBean">select t.* from tableName where id = #{0} and name = #{1} </select>就不使用parameterType, 直接用索引,從0開始
方法二:基于注解(最簡單)
//加注解傳參 public List<XXXBean> getXXXBeanList(@Param("id")String id, @Param("code")String code); //sql語句 <select id="getXXXBeanList" resultType="XXBean">select t.* from tableName where id = #{id} and name = #{code} </select>@Param注解的作用是給參數(shù)命名,參數(shù)命名后就能根據(jù)名字得到參數(shù)值,正確的將參數(shù)傳入sql語句中(一般通過#{}的方式,${}會有sql注入的問題)
方法三:Map封裝
//傳參 HashMap <String,Object> map=new HashMap<String,Object>(); map.put("userName","zhangsan"); map.put("password","123456"); public List<XXXBean> getXXXBeanList(HashMap map); //sql語句 <select id="getXXXBeanList" parameterType="map" resultType="XXBean">select 字段... from XXX where id=#{userName} code = #{passWord} </select>方法四:List封裝
//傳入?yún)?shù) public List<XXXBean> getXXXBeanList(List<String> list); //sql語句 <select id="getXXXBeanList" resultType="XXBean">select 字段... from XXX where id in<foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </select>最后
傳遞list和map在資源消耗上肯定遠大于方法一和方法二,但是有一些特殊的情形需要傳遞list,比如你需要傳遞一個id集合并批量對id進行sql操作然后再返回等等。所以都需要了解。
總結(jié)
以上是生活随笔為你收集整理的Mybatis (ParameterType) 如何传递多个不同类型的参数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 盘点一下全网最有趣的代码注释
- 下一篇: mysql 插入数据后返回该条数据id