1 复习
动态sql
多条件查询 if where 重点!!
双向关联
多对一 一对一
一对多 stud where gid
resultMap 映射级别
列名和实体类属性不一样
Grade student
Id主键 主键id 外键 gid
Select s.id gid.id gid from student s inner join grade g on g.id=s.gid
二级缓存
总配置文件中 设置开启
映射文件中 设置缓存容量
查询语句中 开启缓存
2 choose
类似 switch 只能选一个
![](https://i-blog.csdnimg.cn/blog_migrate/d2f83002df594e4a4bab3c445ce42acb.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/5bad9f9d134f324120dbe7c6144aea09.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/d58e50446cee8f630ec1df35bd1cb27f.gif)
3 foreach
In 动态
// SELECT * FROM student WHERE gid IN (1,2,3)
// 接口
List<Student> getc(List<Integer> gids);
Mapper
<select id="getc" resultType="Student" > select * from student where gid in <foreach collection="list" item="gids" open="(" close=")" separator="," > #{gids}
</foreach>
</select> |
测试
![](https://i-blog.csdnimg.cn/blog_migrate/f63fd387ee57bcd23779d2c137a6efb3.gif)
4 更新 set
不是更新所有的列,只更新改变的列
动态更新 省去根据id查询,可以不用更新所有列
int myupdate(Student student);
<update id="myupdate" parameterType="Student"> UPDATE `j78`.`student` <set> <if test="sname!=null"> `sname` = #{sname}, </if> <if test="tel!=null"> `tel` = #{tel}, </if> <if test="age!=null"> `age` = #{age}, </if> <if test="gid!=null"> `gid` = #{gid} </if>
</set> WHERE `sid` = #{sid} </update> |
![](https://i-blog.csdnimg.cn/blog_migrate/643054445d137b824725e73bfd4f183e.gif)
5 动态增加
目标 sql语句可以 判断 是否执行 可以为null列 ,不用写sql语句
<insert id="addstudent" parameterType="Student"> INSERT INTO `j78`.`student` ( <if test="sname!=null"> `sname` , </if> <if test="tel!=null"> `tel` , </if> <if test="age!=null"> `age`, </if> <if test="gid!=null"> `gid` </if> ) VALUES ( <if test="sname!=null"> #{sname}, </if> <if test="tel!=null"> #{tel}, </if> <if test="age!=null"> #{age}, </if> <if test="gid!=null"> #{gid} </if>
)
</insert> |
测试
//接口 StudentMapper sm=session.getMapper(StudentMapper.class); Student s=new Student(); s.setGid(1); int n=sm.addstudent(s); System.out.println(n); |
6 trim
![](https://i-blog.csdnimg.cn/blog_migrate/5776e20e68178b076d183a9f77ac01bd.gif)
6.1 trim查询
![](https://i-blog.csdnimg.cn/blog_migrate/b59fc5499e6925df1428fba50208f60e.gif)
6.2 set
<update id="myupdate" parameterType="Student"> UPDATE `j78`.`student` <trim prefix="set" suffix=" WHERE `sid` = #{sid}" suffixOverrides=","> <if test="sname!=null"> `sname` = #{sname}, </if> <if test="tel!=null"> `tel` = #{tel}, </if> <if test="age!=null"> `age` = #{age}, </if> <if test="gid!=null"> `gid` = #{gid}, </if> </trim> </update> |
7 总结
动态sql语句
1 动态查询
多条件查询, and(if)
单选 choose
In foreach
2 动态更新
Set +if
3 动态增加
If
4 trim 优化 动态sql , and