mybatis中最常用的Map参数传递
controller
@ApiOperation(value = "多个参数查询")
@GetMapping("findByMapParams")
public ResultMsg findByMapParams(Short gender,String age)
{
Map params = new HashMap<>();
params.put("gender",gender);
params.put("age",age);
List result= employeeMapper.selectByMapParams(params);
return ResultMsg.getMsg(result);
}
mapper
List<Employee> selectByMapParams(Map params);
可以看到使用map来传递多个参数,可以直接使用参数名称进行引用
<select id="selectByMapParams" resultMap="BaseResultMap" parameterType="map">
select * from employee where gender = #{gender} and age = #{age}
</select>
Mybatis 中$与#的区别
1 #是将传入的值当做的形式,eg:select id,name,age from student where id =#{id},当前端把id值1,传入到后台的时候,就相当于 select id,name,age from student where id ='1'.
2 {id},当前端把id值1,传入到后台的时候,就相当于 select id,name,age from student where id = 1.
3 使用#可以很大程度上防止sql注入。(语句的拼接)
4 但是如果使用在order by 中就需要使用 $.
5 在大多数情况下还是经常使用#,但在不同情况下必须使用$.
我觉得#与的区别最大在于:#{} 传入值时,sql解析时,参数是带引号的,而的区别最大在于:#{} 传入值时,sql解析时,参数是带引号的,而{}穿入值,sql解析时,参数是不带引号的。
一 : 理解mybatis中 $与#
在mybatis中的$与#都是在sql中动态的传入参数。
eg:select id,name,age from student where name=#{name} 这个name是动态的,可变的。当你传入什么样的值,就会根据你传入的值执行sql语句。
二:使用$与#
{}: 解析为一个 JDBC 预编译语句(prepared statement)的参数标记符,一个 #{ } 被解析为一个参数占位符 。
${}: 仅仅为一个纯碎的 string 替换,在动态 SQL 解析阶段将会进行变量替换。
name-->cy
eg: select id,name,age from student where name=#{name} -- name='cy'
select id,name,age from student where name=${name} -- name=cy
MyBatis+MySQL 返回插入的主键ID
方法:在mapper中指定keyProperty属性,示例如下:
xml
<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User">
insert into user(userName,password,comment)
values(#{userName},#{password},#{comment})
</insert>
如上所示,我们在insert中指定了keyProperty="userId",其中userId代表插入的User对象的主键属性。
网友评论