mybatis的mapper.xml中select標籤中的parameterType屬性
阿新 • • 發佈:2018-12-10
SqlSession的selectList()與selcetOne()的第二個引數和selectMap()的第三個引數都表示方法的引數
程式碼如下
Flower flower = session.selectOne("com.bjsxt.mapper.FlowerMapper.selById",1);
System.out.println(flower);
mapper.xml檔案配置如下
<?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="com.bjsxt.mapper.FlowerMapper"> <select id="selById" resultType="com.bjsxt.pojo.Flower" parameterType="int"> select * from flower where id=#{id} <!--select * from flower where id=#{0}--> </mapper>
使用索引,從 0 開始 #{0}表示第一個引數,也可以使用#{param1}第一個引數,如果只有一個引數(基本資料型別或 String),mybatis對#{}裡面內容沒有要求只要寫內容即可. 得到的結果如下
DEBUG 2018-09-18 07:02:31 第139行 ==> Preparing: select * from flower where id=? DEBUG 2018-09-18 07:02:31 第139行 ==> Parameters: 1(Integer) DEBUG 2018-09-18 07:02:31 第139行 <== Total: 1 id:1 name:櫻花 price:2.5 production:武漢
可以看到用#{}得到的是佔位符,而改為${}後,需要傳入物件,則程式碼改為如下:
Flower f = new Flower();
f.setId(1);
Flower flower = session.selectOne("com.bjsxt.mapper.FlowerMapper.selById",f);
System.out.println(flower);
mapper.xml檔案
<select id="selById" resultType="com.bjsxt.pojo.Flower" parameterType="com.bjsxt.pojo.Flower"> select * from flower where id=${id} </select>
而結果變為:
DEBUG 2018-09-18 07:10:36 第139行 ==> Preparing: select * from flower where id=1
DEBUG 2018-09-18 07:10:36 第139行 ==> Parameters:
DEBUG 2018-09-18 07:10:37 第139行 <== Total: 1
id:1 name:櫻花 price:2.5 production:武漢
可以看到${}是直接從物件flower中提取{}內的id引數(id引數要有get方法)
總結#{} 和${}的區別
#{} 獲取引數的內容支援 索引獲取,param1 獲取指定位置引數, 並且 SQL 使用?佔位符,若傳入 doller符{} 預設找doller符{內容},內容的 get/set 方法
當需要傳入多個引數時
Map<String, Object> map = new HashMap<>();
map.put("id", 1);
map.put("id2", 2);
List<Flower> list = session.selectList("com.bjsxt.mapper.FlowerMapper.selById2",map);
xml程式碼如下
</select>
<select id="selById2" resultType="com.bjsxt.pojo.Flower" parameterType="map">
select * from flower where id=#{id} or id=#{id2}
</select>
結果如下
DEBUG 2018-09-18 07:26:02 第139行 ==> Preparing: select * from flower where id=? or id=?
DEBUG 2018-09-18 07:26:02 第139行 ==> Parameters: 1(Integer), 2(Integer)
DEBUG 2018-09-18 07:26:02 第139行 <== Total: 2
[id:1 name:櫻花 price:2.5 production:武漢, id:2 name:荷花 price:3.4 production:濟南]
當然,如果改成${}也可以,結果相同,輸出格式變為:
DEBUG 2018-09-18 07:28:46 第139行 ==> Preparing: select * from flower where id=1 or id=2