文章目录
一、方法中多参传入
- 在接口方法的参数前加 @Param属性(否则xml中参数系统无法识别匹配)
- 多个参数mybatis会做特殊处理,将多个参数封装成一个map,#{}就是从map中获取指定的key值
//通过密码和名字查询用户
User selectUserByPwd(@Param("username") String username,@Param("pwd") String pwd);
<select id="selectUserByPwd" resultType="com.xc.entity.User">
select * from user where name = #{username} and pwd = #{pwd}
</select>
- 在接口方法中,参数直接传递Map;(系统则把key作为xml中参数标准)
List<User> getUserByIdAndName(Map<String,Object> map);
<select id="getUserByIdAndName" resultType="com.xc.entity.User" >
select * from user where id = #{id} and name = #{name}
</select>
Map<String, Object> map = new HashMap<>();
map.put("id",1);
map.put("name","zhangsan");
List<User> userByIdAndName = userDao.getUserByIdAndName(map);
二、resultMap自定义结果集
1)属性值介绍
2)级联属性,一对一
3)一对一
4)一对多,嵌套结果集
5)分步查询
6)if判断标签,可以去掉前面多余的and 或者 也可以使用 1=1
7)trim字符串截取
8)foreach循环
9)choose 选择标签
10)update set值 去除最后多余逗号
11)MySql 批量插入
方式一:
方式二:
11)Oracl 批量插入
方式一:
方式二:
12)sql标签-抽取重用sql片段
三、#{}和${}区别
- #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。
- $将传入的数据直接显示生成在sql中。则传入or 1 = 1,则会造成sql注入。
- mybatis 排序order by 动态参数时,使用$.
四、模糊查询
1. sql中字符串拼接
select * from user where name like concat(‘%’,#{name},‘%’); mysql支持两头拼接
select * from user where name like concat(concat(‘%’,#{name}),‘%’);oracle只能一边拼接
2. 使用${}
select * from user where name like ‘% ${name}%’
3.程序中拼接
select * from user where name like #{name}; name = “%” + name + “%”;
4.匹配
select * from user where name ‘%’ || #{name} || ‘%’;
五、日志sql
mybatis-config.xml 核心配置文件中添加。
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
集成springboot yml配置文件
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl