mybatis的mapper.xml中select标签中的parameterType属性

SqlSession的selectList()与selcetOne()的第二个参数和selectMap()的第三个参数都表示方法的参数

代码如下

Flower flower = session.selectOne("com.leesun.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.leesun.mapper.FlowerMapper">	
	<select id="selById" resultType="com.leesun.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.leesun.mapper.FlowerMapper.selById",f);
System.out.println(flower);

mapper.xml文件

<select id="selById" resultType="com.leesun.pojo.Flower" parameterType="com.leesun.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.leesun.mapper.FlowerMapper.selById2",map);

xml代码如下

</select>
	<select id="selById2" resultType="com.leesun.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 

猜你喜欢

转载自blog.csdn.net/qq_40392686/article/details/82762818