mybatis的sql语句关键字的使用方法

来源:互联网 发布:java中的reflection 编辑:程序博客网 时间:2024/06/16 04:47
<?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="cn.ssm.dao.EmpDao">  
  
    <!-- 查询全部的员工 -->  
  <select id="findAll" resultType="cn.ssm.entity.Emp">  
    select * from t_emp  
  </select>  
    
  <!-- if的用法 -->  
  <select id="findByDept" resultType="cn.ssm.entity.Emp" parameterType="cn.ssm.entity.Condition">  
    select * from t_emp  
        <if test="deptno !=null">  
            where deptno = #{deptno}  
        </if>  
  </select>  
    
  <!-- chose的用法 -->  
  <select id="findBySalary" resultType="cn.ssm.entity.Emp" parameterType="cn.ssm.entity.Condition">  
    select * from t_emp  
    <choose>  
        <when test="salary>3000">  
            where sal>#{salary}  
        </when>  
        <otherwise>  
            where sal>3000  
        </otherwise>  
    </choose>  
  </select>  
    
  <!-- where -->  
  <!-- 查询当前部门下,大于当前收入的员工-->  
  <select id="findByDeptAndSalary" resultType="cn.ssm.entity.Emp" parameterType="cn.ssm.entity.Condition">  
    select * from t_emp  
    <where>  
        <if test="deptno !=null">  
            and deptno=#{deptno}  
        </if>  
        <if test="salary!=null">  
            and sal>#{salary}  
        </if>  
    </where>  
  </select>  
    
  <!-- update -->  
  <!-- 更新员工信息 -->  
  <update id="update"  parameterType="cn.ssm.entity.Condition">  
        update t_emp  
        <set>  
            <if test="ename!=null">  
                ename=#{ename}  
            </if>  
            <if test="job!=null">  
                job=#{job}  
            </if>  
        </set>  
        where empno=#{empno}  
  </update>  
    
  <!-- 使用trim代替where -->  
  <!-- 查询 -->  
  <select id="findByDeptAndSalary2" resultType="cn.ssm.entity.Emp" parameterType="cn.ssm.entity.Condition">  
    select * from t_emp  
        <trim prefix="where" prefixOverrides="and" >  
            <if test="deptno!=null">  
                and deptno=#{deptno}  
            </if>  
            <if test="salary !=null">  
                and sal>#{salary}  
            </if>  
        </trim>  
  </select>  
  <!-- 使用trim代替set -->  
  <!-- 更新 -->    
  <update id="update2">  
    update t_emp  
        <trim prefix="set" prefixOverrides="," >   
            <if test="ename!=null">  
                ename=#{ename},  
            </if>  
            <if test="job!=null">  
                job=#{job},  
            </if>  
        </trim>  
        where empno=#{empno}  
  </update>  
    
  <!-- 根据id查询 -->  
  <select id="findById" resultType="cn.ssm.entity.Emp" parameterType="cn.ssm.entity.Condition">  
    select * from t_emp where empno in  
        <foreach collection="empnos" open="(" close=")" separator="," item="id">  
            #{id}     
        </foreach>  
  </select>  
</mapper>  
原创粉丝点击