0
点赞
收藏
分享

微信扫一扫

第3章 动态SQL

南陵王梁枫 2022-08-29 阅读 93

目录/Contents

第3章 动态SQL

学习目标

掌握MyBatis中动态SQL元素的使用

掌握MyBatis的条件查询操作

掌握MyBatis的更新操作

掌握MyBatis的复杂查询操作

学习内容

1 动态SQL中的元素

1.1 使用动态SQL的好处
1.2 动态SQL常用元素

在这里插入图片描述

2 条件查询操作

2.1 <if>元素
<!– 该xml文件中只列出了if元素的动态SQL-->
<if test="username !=null and username !=‘’“>
       and username like concat('%',#{username}, '%')
</if>
<if test="jobs !=null and jobs !=‘’“>
     and jobs= #{jobs}
</if>
2.2 <choose>、<when>、<otherwise>元素
       <!-- 只展示三个组合元素的部分-->
<choose>
        <when test="username !=null and username !=''">
            and username like concat('%',#{username}, '%')
        </when>
        <when test="jobs !=null and jobs !=''">
            and jobs= #{jobs}
        </when>
        <otherwise>and phone is not null</otherwise>
</choose> 
2.3 <where>、<trim>元素
<select id="findCustomerByNameAndJobs" 
          parameterType="com.itheima.pojo.Customer"
          resultType="com.itheima.pojo.Customer">
    select * from t_customer
    <where>
        <if test="username !=null and username !=''">
            and username like concat('%',#{username}, '%')</if>
        <if test="jobs !=null and jobs !=''">
            and jobs= #{jobs}</if>
    </where></select>
     <select id="findCustomerByNameAndJobs" 
          parameterType="com.itheima.pojo.Customer"
          resultType="com.itheima.pojo.Customer">
    select * from t_customer
   <trim prefix="where" prefixOverrides="and" >
        <if test="username !=null and username !=''">
            and username like concat('%',#{username}, '%')</if>
        <if test="jobs !=null and jobs !=''">
            and jobs= #{jobs}</if></trim>
</select>

3 更新操作

3.1 <set>元素
<update id="updateCustomerBySet" parameterType="com.itheima.pojo.Customer">update t_customer 
    <set>
        <if test="username !=null and username !=''">
            username=#{username},</if>
        <if test="jobs !=null and jobs !=''">  jobs=#{jobs},</if>
        <if test="phone !=null and phone !=''">phone=#{phone},</if>
    </set> where id=#{id}
</update> 

4 复杂查询操作

4.1 <foreach>元素的属性

在这里插入图片描述

4.2 <collection>属性的取值
4.3 <foreach>元素迭代数组
<select id="findByArray" parameterType="java.util.Arrays"
         resultType="com.itheima.pojo.Customer">select * from t_customer where id in
    <foreach item="id" index="index" collection="array" 
               open="(" separator="," close=")">	#{id}
    </foreach>
select>
public void findByArrayTest() {
    SqlSession session = MyBatisUtils.getSession(); // 获取SqlSession
    Integer[] roleIds = {2,3}; // 创建数组,封装查询id
    // 执行SqlSession的查询方法,返回结果集
    List<Customer> customers = session.selectList("com.itheima.mapper"
            + ".CustomerMapper.findByArray", roleIds);	
    for (Customer customer : customers) {System.out.println(customer);}
    session.close();
}

在这里插入图片描述

4.4 <foreach>元素迭代List
<select id="findByList" parameterType="java.util.Arrays"
         resultType="com.itheima.pojo.Customer">
    select * from t_customer where id in
    <foreach item="id" index="index" collection="list" 
               open="(" separator="," close=")">
        #{id}
    </foreach>
</select>
public void findByListTest() {
    SqlSession session = MyBatisUtils.getSession();
    List<Integer> ids=new ArrayList<Integer>();
    ids.add(1);  ids.add(2);
    List<Customer> customers = session.selectList("com.itheima.mapper"
            + ".CustomerMapper.findByList", ids);	
    for (Customer customer : customers) {System.out.println(customer);
    } session.close();
}

在这里插入图片描述

4.5 <foreach>元素迭代Map

下面通过一个案例演示如何使用元素迭代Map集合,实现多参数入参查询操作,案例具体实
现步骤如下。
在映射文件CustomerMapper.xml中,添加使用元素迭代Map集合执行批量查询操作的动态SQL。

select * from t_customer where jobs=#{jobs} and id in
#{roleMap}


在测试类MyBatisTest中,编写测试方法findByMapTest(),用于批量查询客户信息。
public void findByMapTest() {
SqlSession session = MyBatisUtils.getSession();
List ids=new ArrayList();
ids.add(1); ids.add(2); ids.add(3);
Map<String,Object> conditionMap = new HashMap<String, Object>();
conditionMap.put(“id",ids); conditionMap.put(“jobs”,“teacher”);
List customers = session.selectList(“com.itheima.mapper”
+ “.CustomerMapper.findByMap”, conditionMap);
for (Customer customer : customers) { System.out.println(customer);}
session.close();
}
执行MyBatisTest测试类的findByMapTest()方法,控制台会输出结果。
在这里插入图片描述

5 案例:学生信息查询系统

5.1 需求
5.2 项目搭建
5.3 数据准备
USE mybatis;
CREATE TABLE dm_student(
    id int(32) PRIMARY KEY AUTO_INCREMENT,
    name varchar(50),  
    major varchar(50),    
    sno varchar(16) );
    # 插入7条数据,其他省略
INSERT INTO dm_student VALUES ('1', '张三', '数学', '10001');
5.4 POJO类准备
public class Student {// 定义变量主键id,姓名name,专业major,学号sno
    private Integer id;  private String name;    
    private String major;  
    private String sno;  
    // 省略getter/setter方法    
    @Override
    public String toString() {
        returnStudent{+ “id=+ id +, name=‘” + name +,           major=" + major  + ", sno=" + sno + '}';}}
5.5 创建映射文件
<mapper namespace="com.itheima.mapper.StudentMapper">
  <select id=“findStudentByNameAndMajor” parameterType=com.itheima.pojo.Student” resultType="com.itheima.pojo.Student">
        select * from dm_student where 1=1	<choose>
            <when test="name !=null and name !=''">
                and name like concat('%',#{name}, '%')</when>
            <when test="major !=null and major !=''"> and major= #{major}</when>
       <otherwise> and sno is not null</otherwise> </choose> 
   </select>
</mapper>
5.6 修改mybatis-config.xml核心配置文件
<mapper resource="com/itheima/mapper/StudentMapper.xml"/>
5.7 编写MyBatisUtils工具类
public class MyBatisUtils {
       private static SqlSessionFactory sqlSessionFactory = null;
       static {	 
	try {
            Reader reader = Resources.getResourceAsReader(“mybatis-config.xml”);	                           SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
	          } catch (Exception e) {e.printStackTrace();} 	}
        public static SqlSession getSession() {
              return sqlSessionFactory.openSession();}
}
5.8 编写测试方法
public void findStudentByNameOrMajorTest() {
    SqlSession session=MyBatisUtils.getSession();
    Student student=new Student();
    student.setName("张三"); 
    student.setMajor("英语");
    List<Student> students = session.selectList("com.itheima.mapper"
            + ".StudentMapper.findStudentByNameAndMajor",student);
    for (Student student2 : students) {System.out.println(student2);}
    session.close();
}
5.9 查看运行结果
5.10 多条件查询案例结果分析
5.11 修改映射文件
<select id="findByList" parameterType="java.util.List"
        resultType="com.itheima.pojo.Student">
    		select * from dm_student where id in
    <foreach item="id" index="index" collection="list"
             open="(" separator="," close=")">
        #{id}
    </foreach>
</select>
5.12 编写测试方法
public void findByListTest() {
    SqlSession session = MyBatisUtils.getSession();
    List<Integer> ids=new ArrayList<Integer>();
    for(int i =1;i<5;i++){ 
	ids.add(i);}
    List<Student> students = session.selectList("com.itheima.mapper"
            + ".StudentMapper.findByList", ids);
    for (Student student : students) { System.out.println(student);}
    session.close();
}
举报

相关推荐

0 条评论