Mybatis学习笔记(三)动态SQL标签详解
【摘要】 Mybatis学习笔记(三)动态SQL标签详解
1、基本环境搭建
建立数据库
建表语句
CREATE TABLE `t_teacher` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`teacherName` varchar(100) DEFAULT NULL,
`class_name` varchar(100) DEFAULT NULL,
`address` varchar(100) DEFAULT NULL,
`birth_date` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
创建对应实体类
public class Teacher {
private Integer id;
private String name;
private String course;
private String address;
private Date brith;
//省略get、set、toString方法
}
Dao
public interface TeacherDao {
public Teacher getTeacherById(Integer id);
}
xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace:名称空间;写接口的全类名,相当于告诉Mybatis这个配置文件是实现哪个接口的 -->
<mapper namespace="com.dong.dao.TeacherDao">
<select id="getTeacherById" resultMap="teacherMap">
select * from t_teacher where id = #{id}
</select>
<resultMap type="com.dong.bean.Teacher" id="teacherMap">
<id column="id" property="id"/>
<result column="address" property="address"/>
<result column="teacherName" property="name"/>
<result column="birth_date" property="brith"/>
<result column="class_name" property="course"/>
</resultMap>
</mapper>
项目整体结构
测试
@Test
public void test() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
Teacher empById;
//获取和数据库的一次会话:getConnection()
SqlSession openSession = sqlSessionFactory.openSession();
try {
//使用SqlSession操作数据库,获取dao接口的实现
TeacherDao mapper = openSession.getMapper(TeacherDao.class);
empById = mapper.getTeacherById(1);
System.out.println(empById);
} finally {
//关闭连接
openSession.close();
}
}
查询成功
2、动态SQL——if标签
dao
xml
<resultMap type="com.dong.bean.Teacher" id="teacherMap">
<id column="id" property="id"/>
<result column="address" property="address"/>
<result column="teacherName" property="name"/>
<result column="birth_date" property="brith"/>
<result column="class_name" property="course"/>
</resultMap>
<!--if:判断-->
<select id="getTeacherByCondition" resultMap="teacherMap">
select * from t_teacher where
<!--test="":编写条件
id!=null:取出javaBean属性中的id的值,判断是否为空
-->
<if test="id!=null">
id > #{id} and
</if>
<if test="name!=null && !name.equals("")">
teacherName like #{name} and
</if>
<if test="brith!=null">
birth_date > #{brith}
</if>
</select>
测试
@Test
public void test() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取和数据库的一次会话:getConnection()
SqlSession openSession = sqlSessionFactory.openSession();
try {
//使用SqlSession操作数据库,获取dao接口的实现
TeacherDao mapper = openSession.getMapper(TeacherDao.class);
Teacher teacher = new Teacher();
teacher.setId(1);
teacher.setName("%a%");
teacher.setBrith(new Date());
List<Teacher> teacherByCondition = mapper.getTeacherByCondition(teacher);
System.out.println(teacherByCondition);
} finally {
//关闭连接
openSession.close();
}
}
在XML写判断条件很容易出现写的字符需要转义
W3cSchool转义对照表
3、动态SQL——Where标签
在使用mybatis的动态sql时,有时候遇到根据条件判断添加where后面的筛选条件,会出现多余的“and”或者“or。
使用Where标签
注意去掉t_teacher本来后面的where
可以看到数据查出来了
where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。
4、动态SQL——trim标签
<select id="getTeacherByCondition" resultMap="teacherMap">
select * from t_teacher
<!--
prefix="":前缀,为我们下面的sql整体添加一个前缀
prefixOverrides="":取出整体字符串前面多余的字符
suffix="":为整体添加一个后缀
suffixOverrides="":后面哪个多了可以去掉
-->
<trim prefix="where" suffixOverrides="and">
<if test="id!=null">
id > #{id} and
</if>
<if test="name!=null && !name.equals("")">
teacherName like #{name} and
</if>
<if test="brith!=null">
birth_date > #{brith} and
</if>
</trim>
</select>
测试
5、动态SQL——foreach标签
dao
xml
<select id="getTeacherByIdIn" resultMap="teacherMap">
select * from t_teacher where id in
<!--
index="":索引
如果遍历的是一个list:
index:指定的变量保存了当前索引
item:保存当前便利的元素的值
如果遍历的是一个map:
index:指定的变量就是保存了当前遍历的元素的key
item:就是保存当前遍历的元素的值
collection="" :指定遍历集合的key
item="" : 每次遍历出的元素起一个变量名方便引用
open="" :以什么开始
close="" : 以什么结束
separator="" : 每次遍历的元素的分隔符
-->
<foreach collection="ids" open="(" close=")" item="id_item" separator=",">
</foreach>
</select>
测试
6、动态SQL——choose分支选择
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
dao
xml
<select id="getTeacherByConditionChoose" resultMap="teacherMap">
select * from t_teacher
<where>
<choose>
<when test="id!=null">
id=#{id}
</when>
<when test="name!=null">
teacherName like #{name}
</when>
<when test="brith!=null">
brith_data = #{brith}
</when>
<!-- 其他 -->
<otherwise>
<!-- 查所有 -->
1=1
</otherwise>
</choose>
</where>
</select>
测试
可以看见只按照了**id查询
7、动态SQL——使用if结合set完成mybatis动态更新
dao
xml
测试
虽然条件拼上了,但是逗号还在,这时我们可以使用set标签替换语句中的set
成功更新
觉得博主写的不错的读者大大们,可以点赞关注和收藏哦,谢谢各位!
process=image/format,png#pic_center)
【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)