-
需求: 在一個sql 中需要傳遞多個參數,這時候,這麼傳遞和在<select>中獲取值呢,有一條sql 一:傳遞單個值:需要傳遞的參數:id 方式一; 接口 中 find(Integer id); <select> select * from user where id=#{id} </select> 方式二: <select> select * from user where id=#{xxx} //傳遞單個值的時候,這裏面寫錯都還可以傳遞過去 </select> 二:傳遞多個值 需要傳遞的參數有id age 呢 錯誤: 這時候,假如想第一次那樣,直接傳遞 <select> select * from user where id=#{id} AND age=#{age} </select> 會報錯 use: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [arg1, arg0, param1, param2] 假如你還想直接傳遞參數的話 ××方式1:可以傳遞params1,params2,意思是 底層map集合中的第幾個元素 接口中 find (Integer id,Integer age) <select> select * from user where id=#{param1} AND age=#{param2} </select> 在調用的時候,傳遞兩個參數就可以了 ××方式2:將需要傳遞的參數,封裝在JavaBean類中,使用POJO來傳遞參數 JavaBean中 User Integer id; Integer age; 接口中 find (User user) <select> select * from user where id=#{id} AND age=#{age} </select> ××方式3:將參數封裝在map集合中例如 --》 接口中 find(Map<String,Object> map); --》 <select> select * from user where id=#{aaa} AND age =#{bbb} </select> --》 調用的時候: Map<String,Object> map = new HashMap<String,Object>(); map.put("aaa",5); map.put("bbb",12); userDao.find(map); 注意,這裏根據的是map 的key來找value的 提出一個問題,假如需要傳遞的參數,既有單個參數,又有對象呢,這怎麼傳遞? 解決1: 接口中, find(Integer id,User user); 使用POJO傳遞,還有上面多個參數傳遞的第一種 <select> select * from user where id =#{param1} AND age =#{param2.age} </select> 追加,使用map來封裝這兩個參數 --》接口中: find(Map<String , Object> map); --》 使用 <select> select * from user where id =#{aaa} AND age=#{bbb.age} AND name=#{bbb.name} </select> --》調用: Map<String,Object> map = new HashMap<String , Object>(); User user= new User (name,age); map.put("aaa",1); map.put("bbb",User);
Mybatis中Java向SQL中傳值的幾種方式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.