mybatis学习记录 (二) 映射文件
1. 参数处理
在上个博客中,我们可以看到UserMapper.java和UserMapper.xml文件中有这相应的对应,在这里我先将这两个文件的代码展示出来。
1.1 文件展示
UserMapper.java
package com.jt;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.Map;
public interfaceUserMapper {
public User selectUser(int id);
//单个参数传递
public UserselectUserByIdAndName(@Param("id") Integer id,@Param("username") String username);
// 多个参数传递
public UserselectUserByIdAndNameUseMap(Map map);
//多个参数传递public Integer insertUser(User user);
public boolean updateUser(User user);
public Integer deleteUserById(int id);
}
UserMapper.xml文件
select * from test01 where id = #{id}select * from test01 where id = #{id} and username=#{username}select * from test01 where id = #{id} and username=#{username}
insert into test01 (username,password) values(#{username},#{password})
update test01 set username=#{username} where id=#{id}
delete from test01 where id=#{id}
1.2 文件分析
在UserMapper.java接口文件中,传递的参数有,单个参数,多个参数的情况。
1.2.1 单个参数 直接使用#{}或者${}去接收参数即可
public User selectUser(int id);
//单个参数传递select * from test01 where id = #{id}
1.2.2 多个参数参数 总结 #{}或者${}这种方式取值,本质是在一个Map对象中根据key值去获取参数值。
(1)使用@Param定义在xml文件中获取参数的key值
public UserselectUserByIdAndName(@Param("id") Integer id,@Param("username") String username);
// 多个参数传递select * from test01 where id = #{id} and username=#{username}
(2)或者不用@Param,在xml文件中使用#{param1}这种形式来获取相应参数的值
public UserselectUserByIdAndName(Integer id,String username);
// 多个参数传递select * from test01 where id = #{param1} and username=#{param2}
(3)使用pojo类来传递参数
public Integer insertUser(User user);
insert into test01 (username,password) values(#{username},#{password})
(4)使用map来传递参数
public UserselectUserByIdAndNameUseMap(Map map);
//多个参数传递select * from test01 where id = #{id} and username=#{username}
1.2.3 #{}和${}的区别 {} 使用了预编译 ${}没有使用预编译,安全性相对比较低。
下图可以清晰的解释两者的区别。
【mybatis学习记录 (二) 映射文件】
文章图片
推荐阅读
- 20170612时间和注意力开销记录
- 由浅入深理解AOP
- 继续努力,自主学习家庭Day135(20181015)
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- mybatisplus如何在xml的连表查询中使用queryWrapper
- mybatisplus|mybatisplus where QueryWrapper加括号嵌套查询方式
- MybatisPlus|MybatisPlus LambdaQueryWrapper使用int默认值的坑及解决
- MybatisPlus使用queryWrapper如何实现复杂查询
- python学习之|python学习之 实现QQ自动发送消息
- 一起来学习C语言的字符串转换函数