首页
技术小册
AIGC
面试刷题
技术文章
MAGENTO
云计算
视频课程
源码下载
PDF书籍
「涨薪秘籍」
登录
注册
第一章:简介
第二章:环境搭建
第三章:if 判断
第四章:where 查询条件
第五章:trim 自定义字符串截取
第六章:choose 分支选择
第七章:set 更新
第八章:foreach 遍历
第九章:foreach 批量插入(Mysql)
第十章:foreach 批量插入(Oracle)
第十一章:内置参数
第十二章:bind 绑定
第十三章:抽取可重用的 SQL 片段
当前位置:
首页>>
技术小册>>
Mybatis合辑3-Mybatis动态SQL
小册名称:Mybatis合辑3-Mybatis动态SQL
- 示例: - EmployeeMapper.java ``` package com.sunxiaping.mapper; import com.sunxiaping.domain.Employee; import java.util.List; public interface EmployeeMapper { List<Employee> getEmpsByConditionIf(Employee employee); } ``` - EmployeeMapper.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"> <mapper namespace="com.sunxiaping.mapper.EmployeeMapper"> <select id="getEmpsByConditionIf" resultType="com.sunxiaping.domain.Employee"> SELECT id as id,last_name as lastName,gender as gender,email as email FROM employee WHERE 1 = 1 <!-- test:条件判断表达式OGNL --> <if test="id != null"> AND id = #{id,jdbcType=INTEGER} </if> <if test="lastName != null and lastName != ''"> AND last_name LIKE #{lastName,jdbcType=VARCHAR} </if> <if test="gender != null and gender != ''"> AND gender = #{gender,jdbcType=VARCHAR} </if> <if test="email != null and email != ''"> AND email = #{email,jdbcType=VARCHAR} </if> </select> </mapper> ``` - 测试: ``` package com.sunxiaping; import com.sunxiaping.domain.Employee; import com.sunxiaping.mapper.EmployeeMapper; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; public class EmployeeTest { SqlSessionFactory sqlSessionFactory = null; SqlSession sqlSession = null; EmployeeMapper employeeMapper = null; @Before public void before() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); sqlSession = sqlSessionFactory.openSession(true); employeeMapper = sqlSession.getMapper(EmployeeMapper.class); } @After public void after() { if (null != sqlSession) { sqlSession.close(); } } @Test public void testFindById() { Employee example = new Employee(); example.setId(1); example.setGender("男"); List<Employee> employeeList = employeeMapper.getEmpsByConditionIf(example); System.out.println("employeeList = " + employeeList); } } ```
上一篇:
第二章:环境搭建
下一篇:
第四章:where 查询条件
该分类下的相关小册推荐:
Java语言基础16-JDK8 新特性
Java并发编程
Java必知必会-JDBC
Java并发编程实战
深入理解Java虚拟机
Mybatis合辑2-Mybatis映射文件
Mybatis合辑1-Mybatis基础入门
Java语言基础7-Java中的异常
Java语言基础13-类的加载和反射
SpringBoot零基础到实战
Java语言基础10-Java中的集合
Mybatis合辑4-Mybatis缓存机制