详解Mybatis之动态sql问题(下)

简介: 详解Mybatis之动态sql问题(下)

3.4 set标签

👉功能

主要用于解决set关键字及多出一个【,】问题

👉用法案例

修改员工的信息

代码示例如下:

①在EmployeeMapper接口中定义修改员工的信息的方法

//修改员工的信息
public void updateEmp(Employee employee);

②在EmployeeMapper接口对应的映射文件中书写相应的sql

问题版(会出现多一个【,】问题

<update id="updateEmp">
    update
        tbl_employee
    set
        <if test="lastName != null">
            last_name=#{lastName}  ,
        </if>
        <if test="email != null">
            email=#{email}  ,
        </if>
        <if test="salary != null">
            salary=#{salary} ,
        </if>
    where
        id=#{id}
</update>

set标签解决问题版

<update id="updateEmp">
    update
        tbl_employee
    <set>
        <if test="lastName != null">
            last_name=#{lastName}  ,
        </if>
        <if test="email != null">
            email=#{email}  ,
        </if>
        <if test="salary != null">
            salary=#{salary} ,
        </if>
    </set>
    where
        id=#{id}
</update>

③测试

@Test
public void test03(){
    try {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //通过SqlSessionFactory对象调用openSession();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取EmployeeMapper的代理对象
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        //动态参数
        Employee employee=new Employee();
        employee.setId(1);
        employee.setLastName("tom");
        employee.setSalary(16800.0);
        employeeMapper.updateEmp(employee);
xml
    } catch (IOException e) {
        e.printStackTrace();
    }
}

使用问题版的sql进行测试

使用set标签解决问题版的sql进行测试

3.5 choose标签

👉功能

类似java中if-else【switch-case】结构

👉应用场景

应用于单个条件不确定的业务场景

👉用法案例

不指定查询条件,查询对应的员工信息(单个条件不确定的)

代码示例如下:

①在EmployeeMapper接口书写相应的方法

//不指定查询条件,查询对应员工信息(单个条件不确定的)
public List<Employee> selectEmpByOneOpr(int empId);

②在EmployeeMapper接口对应的映射文件中书写相应的sql

<!--  根据查询条件查找对应的员工信息(条件不确定) 动态的sql(trim标签优化版)  -->
<select id="selectEmpByOneOpr" resultType="employee">
    SELECT
        `id`,
        `last_name`,
        `email`,
        `salary`,
        `dept_id`
    FROM
        `tbl_employee`
    <where>
        <choose>
            <when test="id !=null">
                id=#{id}
            </when>
            <when test="lastName != null">
                last_name=#{lastName}
            </when>
            <when test="email != null">
                email=#{email}
            </when>
            <otherwise>
                salary=#{salary}
            </otherwise>
        </choose>
    </where>
</select>

③测试

@Test
public void test04(){
    try {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //通过SqlSessionFactory对象调用openSession();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取EmployeeMapper的代理对象
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        List<Employee> employees = employeeMapper.selectEmpByOneOpr(1);
        System.out.println(employees);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

3.6 foreach标签

👉功能

类似java中for循环

👉标签属性

  • collection要迭代的集合
  • item当前从集合中迭代出的元素
  • separator元素与元素之间的分隔符
  • open开始字符
  • close结束字符

👉应用场景

🚩 ①遍历迭代

用法案例

通过多个id获取员工的信息 【EmpIds:员工id的集合】

代码示例如下:

a.在EmployeeMapper接口定义相应的方法

/**
 * 通过多个id获取员工的信息 【EmpIds:员工id的集合】
 * @param EmpIds
 * @return
 */
public List<Employee> selectEmpByIds(@Param("ids") List<Integer> EmpIds);

b.在EmployeeMapper接口对应的映射文件中定义相应的sql

<select id="selectEmpByIds" resultType="employee">
        SELECT
            `id`,
            `last_name`,
            `email`,
            `salary`,
            `dept_id`
        FROM
            `tbl_employee`
        <where>
            `id` in
            (
            <foreach collection="ids" item="id" separator=",">
                #{id}
            </foreach>
            )
        </where>
    </select>

c.测试

@Test
public void test04(){
    try {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //通过SqlSessionFactory对象调用openSession();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取EmployeeMapper的代理对象
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        List<Employee> employees = employeeMapper.selectEmpByOneOpr(1);
        System.out.println(employees);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

🚩②批量导入

用法案例

批量添加员工数据

代码示例如下:

a.在EmployeeMapper接口定义相应的方法

//批量添加员工数据
    public void batchInsertEmp(@Param("emps") List<Employee> employees);

b.在EmployeeMapper接口对应的映射文件中定义相应的sql

// 批量添加员工数据,使用insert标签书写相应的sql
<insert id="batchInsertEmp">
    insert into
        tbl_employee(last_name,email,salary)
    values
        <foreach collection="emps" item="emp" separator=",">
            (#{emp.lastName},#{emp.email},#{emp.salary})
        </foreach>
</insert>

c.测试

@Test
public void test06(){
    try {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //通过SqlSessionFactory对象调用openSession();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取EmployeeMapper的代理对象
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        //定义要添加的员工集合
       List<Employee> list=new ArrayList<>();
       list.add(new Employee("zhangsan","sdhjsd@qq.com",6700.0));
       list.add(new Employee("wangwu","dddhjsd@123.com",9700.0));
        employeeMapper.batchInsertEmp(list);
        sqlSession.commit();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

3.7 sql标签

👉功能

提取可重用SQL片段

❗注意

该SQL片段可以是一个完整的sql语句,也可以是一个sql语句中的某个片段)

👉用法案例

使用sql标签对3.6小节中的应用场景1的案例里映射文件里的的”select xxx,xxxx,xxx from

xxxx”部分提取出来,作为一个可重用的sql片段,在select>标签内引入该sql片段

代码示例如下:

①使用sql标签抽取映射文件中”select xxx,xxxx,xxx from xxxx”部分片段作为可重用的sql片段

<!-- 抽取映射文件中”select xxx,xxxx,xxx from xxxx”部分片段作为可重用的sql片段   -->
<sql id="select_employee">
        SELECT
            `id`,
            `last_name`,
            `email`,
            `salary`,
            `dept_id`
        FROM
            `tbl_employee`
    </sql>
    <select id="selectEmpByIds" resultType="employee">
        <!--  将刚才抽取的sql片段select_employee引入进来  -->
        <include refid="select_employee"></include>
        <where>
            `id` in
            (
            <foreach collection="ids" item="id" separator=",">
                #{id}
            </foreach>
            )
        </where>
    </select>

②测试运行

相关文章
|
4天前
|
SQL Java 测试技术
3、Mybatis-Plus 自定义sql语句
这篇文章介绍了如何在Mybatis-Plus框架中使用自定义SQL语句进行数据库操作。内容包括文档结构、编写mapper文件、mapper.xml文件的解释说明、在mapper接口中定义方法、在mapper.xml文件中实现接口方法的SQL语句,以及如何在单元测试中测试自定义的SQL语句,并展示了测试结果。
3、Mybatis-Plus 自定义sql语句
|
1天前
|
SQL 关系型数据库 MySQL
解决:Mybatis-plus向数据库插入数据的时候 报You have an error in your SQL syntax
该博客文章讨论了在使用Mybatis-Plus向数据库插入数据时遇到的一个常见问题:SQL语法错误。作者发现错误是由于数据库字段中使用了MySQL的关键字,导致SQL语句执行失败。解决方法是将这些关键字替换为其他字段名称,以避免语法错误。文章通过截图展示了具体的操作步骤。
|
23天前
|
SQL Java 数据库连接
idea中配置mybatis 映射文件模版及 mybatis plus 自定义sql
idea中配置mybatis 映射文件模版及 mybatis plus 自定义sql
38 3
|
1月前
|
SQL Java 数据库连接
mybatis动态SQL常用语法总结
MyBatis 使用 OGNL 表达式语言处理动态SQL,如 `if` 标签进行条件判断,`choose`、`when`、`otherwise` 实现多条件选择,`where`、`set` 管理SQL关键字,`trim` 提供通用修剪功能,`foreach` 遍历集合数据。`sql` 和 `include` 用于代码重用,`selectKey` 处理插入后的返回值。参数传递支持匿名、具名、列表、Map、Java Bean和JSON方式。注意SQL转义及使用合适的jdbcType映射Java类型。
50 7
|
2月前
|
SQL Java 数据库连接
深入探索MyBatis Dynamic SQL:发展、原理与应用
深入探索MyBatis Dynamic SQL:发展、原理与应用
|
2月前
|
SQL 缓存 Java
Java框架之MyBatis 07-动态SQL-缓存机制-逆向工程-分页插件
Java框架之MyBatis 07-动态SQL-缓存机制-逆向工程-分页插件
|
2月前
|
SQL Java 数据库连接
MyBatis动态SQL
MyBatis动态SQL
35 0
|
4天前
|
Java 关系型数据库 MySQL
1、Mybatis-Plus 创建SpringBoot项目
这篇文章是关于如何创建一个SpringBoot项目,包括在`pom.xml`文件中引入依赖、在`application.yml`文件中配置数据库连接,以及加入日志功能的详细步骤和示例代码。
|
5天前
|
数据库
elementUi使用dialog的进行信息的添加、删除表格数据时进行信息提示。删除或者添加成功的信息提示(SpringBoot+Vue+MybatisPlus)
这篇文章介绍了如何在基于SpringBoot+Vue+MybatisPlus的项目中使用elementUI的dialog组件进行用户信息的添加和删除操作,包括弹窗表单的设置、信息提交、数据库操作以及删除前的信息提示和确认。
elementUi使用dialog的进行信息的添加、删除表格数据时进行信息提示。删除或者添加成功的信息提示(SpringBoot+Vue+MybatisPlus)
|
5天前
|
Java 数据库 Spring
MyBatisPlus分页插件在SpringBoot中的使用
这篇文章介绍了如何在Spring Boot项目中配置和使用MyBatis-Plus的分页插件,包括创建配置类以注册分页拦截器,编写测试类来演示如何进行分页查询,并展示了测试结果和数据库表结构。
MyBatisPlus分页插件在SpringBoot中的使用