MyBatis 的一个强大的特性之一通常是它的动态 SQL 能力。 如果你有使用 JDBC 或其他 相似框架的经验,你就明白条件地串联 SQL 字符串在一起是多么的痛苦,确保不能忘了空 格或在列表的最后省略逗号。动态 SQL 可以彻底处理这种痛苦。
基本标签:
ifchoose (when, otherwise)trim (where, set)foreachif 用在处理where后面跟一个条件
List<Employee> queryEmployee(@Param("name") String name,@Param("gradeid") int gradeid);当方法有多个的参数 需要使用@Param指明将形参给xml文件中的那个参数
说明:
当第一个when标签执行时后面的when标签将不会执行
如果查询语句后面有多个条件 如果 第一个 if 语句成立则将在语句前面加上 where 并且去掉 if 语句中的 and 或者 or 关键字(简化了 jdbc 中 SQL 凭借中的 where 1=1 的操作)
<select id="queryByIntroduceAndCityId" resultType="ToursInfo"> SELECT id,introduce,pubTime,price,cityId from toursInfo <where> <if test="intro!=null"> and introduce like CONCAT('%',#{intro},'%') </if> <if test="cId!=null"> and cityId =#{cId} </if> </where> </select>场景: 更新 页面将需要更新的值传到后台 如果哪个属性不需要更新就可以使用
映射文件
<update id="updateEmployee"> UPDATE employee <set> <if test="name1 !=null">`NAME`=#{name1},</if> <if test="sex !=null">sex=#{sex},</if> <if test="hiredate !=null">hiredate=#{hiredate},</if> <if test="dept.deptno !=null">deptno=#{dept.deptno}</if> </set> where id=#{id} </update>测试类
// 1.获取InputStream InputStream iStream = Test.class.getClassLoader().getResourceAsStream("config.xml"); // 2.获取sqlsessionfactory SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(iStream); // 3.获取sqlsession SqlSession session = factory.openSession(); // 4.通过代理获取接口的对象 EmployeeDao eDao = session.getMapper(EmployeeDao.class); //更新 Employee employee=new Employee(); employee.setId(47); Dept dept=new Dept(); /* dept.setDeptno(1);*/ employee.setDept(dept); employee.setName1("彭大大"); eDao.updateEmployee(employee); session.commit();Sql语句:DELETE from employee where id in ( 39,40,12) id为动态的 xml中 item="id"代表循环遍历的临时变量名 collection=“list” 参数为List集合 该属性值为list
<delete id="deleteEmployee"> DELETE from employee where id in <foreach collection="list" open="(" close=")" separator="," item="id" > #{id} </foreach> </delete>测试类
public static void main(String[] args) { // 1.获取InputStream InputStream iStream = Test.class.getClassLoader().getResourceAsStream("config.xml"); // 2.获取sqlsessionfactory SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(iStream); // 3.获取sqlsession SqlSession session = factory.openSession(); // 4.通过代理获取接口的对象 EmployeeDao eDao = session.getMapper(EmployeeDao.class); List ids=new ArrayList(); //in(39,40,12) ids.add(17); ids.add(18); eDao.deleteEmployee(ids); session.commit(); }参数为map集合 批量删除 并限制部门编号 sql: DELETE from employee where id in(37,45,47) and deptno=2 分析:1个参数为集合,1个参数为单个值 Foreach遍历Map通过key取值 xml
<delete id="deleteEmployee"> DELETE from employee where id in <foreach collection="ids" open="(" close=")" separator="," item="id"> #{id} </foreach> and deptno=#{deptno} </delete>测试类: 分析图:
