基本类型:前端
基本类型,参数名称与占位符中的名称无关。java
#{} 传入值时,sql解析时,参数是带引号的sql
若是用了@Param("xxx") ,则mybatis会自动生成map做为入参,那么参数名称则必须与占位符一致session
<select id="findById" parameterType="int" resultType="cn.wh.vo.Role"> select * from t_role where id = #{xxxid} </select>
测试:mybatis
@Test public void testSelectOne(){ Role role = (Role)session.selectOne("cn.wh.mapper.RoleMapper.findById",1); System.out.println(role.getName()); }
自定义类型app
自定义类型做为参数,自定义类中须要为为属性提供get方法,若是没有提供get方法,那么会根据占位符中的名称去反射获取值,若是占位符中的名称和属性不一致,那么报ReflectionException。测试
<select id="findListBypage" parameterType="cn.wh.util.PageUtil" resultType="Role"> select * from t_role limit #{index},#{size} </select>
测试:code
@Test public void testPage1(){ PageUtil pu = new PageUtil(); pu.setIndex(3); pu.setSize(3); List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.findListBypage", pu); for(Role r:list){ System.out.println(r.getName()); } }
Mapxml
Map做为参数类型,key和占位符中的名称一致便可,若是名称不一致那么将会把null,传递到占位符中。排序
注意:#{}占位符不能解决一下 3 类问题:
表名是动态的: Select * from #{table_name}
列名是动态的:Select #{column_name} from t_role
排序列是动态的: Select * from t_role order by #{columu}
${}传入值,sql解析时,参数是不带引号的。
所以${}参数不能为基本数据类型,只能为自定义类型和map
<!-- 查询全部 --> <select id="findAll" parameterType="map" resultType="cn.wh.vo.Role"> select * from ${tableName} </select>
测试:
@Test public void testSelectList(){ Map<String,String> map = new HashMap<String,String>(); map.put("tableName", "t_role"); List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.findAll",map); for(Role role:list){ System.out.println(role.getId()+"----"+role.getName()); } }
做为链接符使用:
<select id="selectLike1" parameterType="map" resultType="Role"> select *from t_role where name like '${name}%'; </select>
测试:
@Test public void testLike2(){ Map<String,String> map = new HashMap<String,String>(); map.put("name", "黄"); List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.selectLike1",map); for(Role r:list){ System.out.println(r.getName()); } }
在mybatis中的$与#都是在sql中动态的传入参数。
eg:select id,name,age from student where name=#{name} 这个name是动态的,可变的。当你传入什么样的值,就会根据你传入的值执行sql语句。
#{}: 解析为一个 JDBC 预编译语句(prepared statement)的参数标记符,一个 #{ } 被解析为一个参数占位符 。
${}: 仅仅为一个纯碎的 string 替换,在动态 SQL 解析阶段将会进行变量替换。
例子:
eg 1: select id,name,age from student where name=#{name} ;
解析为:select id,name,age from student where name='cy';
eg 2: select id,name,age from student where name=${name};
解析为:select id,name,age from student where name=cy;