MyBatis if 标签

if 标签在mybatis的开发工作中主要用于where查询、insert插入和update更新三种操作中,本文接下来会对每种操作中的 if 标签做详细讲述.

where 查询中使用<if>标签:

<mapper namespace="cn.mybatis.mapper.EmployeeMapper">
  <select id="selectEmployeeByIdLike" resultTypem"cn.mybatis.domain.Employee">
    SELECT * FROM tb_employee WHERE state = 'ACTIVE'
    <!-- 可选条件,如果传进来的参数有id属性,则加上id查询条件-->
    <if test="id != null">
        and id = #{id}
    </if>
  </select>
</mapper>

以上语句提供了一个可选的根据id查找Employee的功能。如果没有传入id,那么所有处于"ACTIVE"状态的Employee都会被返回。反之,若传入了id,那么就会把查找id内容的Employee结果返回。

public Interface EmployeeMapper {
    List<Employee> selectEmployeeByIdLike (HashMap<String,Object> params);
}

以上代码提供了一个和EmployeeMapper.xml中的select元素的id同名的方法,需要注意的是,selectEmployeeByIdLike 接收一个 HashMap 作为参数。

public static void main(string[] args) throws Exception
{
    // 读取mybatis-config.xml 文件
    Inputstream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    // 初始化mybatis,创建SqlSessionFactory 类的实例
    sqlsessionFactory sqlSessionEactory = new sqlsessionFactoryBullder().build(inputStream);
    // 创建Session实例
    sqlSesaion seasion = sqlsessionFactory.openSession();
    DynamicsQlTest t = new DynamicSQITest();
    t.testSelectEmployeeByIdLike(sesion);
    // 提交事务
    sesion.commit();
    // 关闭Session
    session.close();
}

// 测试<select id="selectEmployeeByIdLike"...>
public void testSelectemployeeByIdLike(Sqlsession session)
{
    // 获得EmployeeMapper接口的代理对象
    EmployeeMapper em = session.getMapper(EmployeeMapper.class);
    // 创建一个HashMap存储参数
    HashMap<String, Object> params = new HashMap<String, Object>();
    // 设置id属性
    params.put("id", 1);
    // 调用EmployeeMapper接口的selectEmployeeByIdLike方法
    List<Employee> list = em.selectEmployeeByIdLike(params);
    // 查看查询结果
    list.foEach(employee -> System.out.printIn(employee));
}

运行上面的main方法,其通过SqlSession的getMapper(Class<T> type)方法获得mapper接口的代理对象EmployeeMapper。调用selctEmployeeByIdLike方法时会执行EmployeeMapper.xm中<select id="selctEmployeeByIdLike".../>元素中定义的sql语句。控制台显示如下:

DEBUG [main]==> Preparing: SELBCT * FRON tb_employee WHERE state = 'ACTIVE' and id= ?
DEBUG [main]==> Parameters:
DEBUG [main]<== Total:2
Employee [id=1,loginname=jack,password=123456,name=马云,sex=男,age=26,phone=13900000001,sal=9800.0,state=ACTIVE]

可以看到,执行的sql语句中因为传入了id属性,所以sql语句中包含了“and id= ?”,查询返回的Emplyee对象就是"id"为1的对象。

接下来注释以下代码:

// params.put("id",1);

再次执行main方法,控制台显示如下:

DEBUG [main]==> Breparing: SBLECT * FROM tb_employee WHERE state = 'ACTVE'
DBBUG [main]--> Parameters:
DEBUG [main]<== Total:4
DEBUG [main]<==
Employee [id=1,loginname=jack,password-123456,name=马云,sex=男,age=26,phone=13900000001,sal=9800.0,state=ACTIVE]
Employee [id=2,loginname=rose,password-123456,nanme=黛西,sex=女,age=21,phone=13900000002,sa1=6800.0,state=ACTIVE]
Employee [id-3,loginname=tom,password=123456,name=汤姆,sex=男,age=25,phone=13900000003,sa1=8800.0,state=ACTIVE]
Employee [id-4,loginname=alice,password=123456,name=爱丽丝,sex=女,age=20,phone=13900000004,sal=5800.0,state=ACTIVE]

可以看到,由于传递的HashMap中没有id属性,故执行的sql语句中不再包含“and id=?”,查询返回了所有state='ACTIVE'的数据。

如果想通过两个条件搜索该怎么办呢? 很简单,只要多加入一个条件即可。

<select id="selectEmgloyeeByLoginLike" resultType="cn.mybatis.domain.Employee">
SELECT * FROM tb_employee WHERE state = 'ACTIVE'
<!-- 两个可选条件,例如登录功能的登录名和密码查询-->
<if test="loginname != null and password != null">
and loginname = #{loginname} and password = #{password)
</if>
</select>
List<Employee> selectEmployeeByLoginLike(HashMap<String,Object> params) ;

public void testSelectEmployeeByLoginLike(SqlSession session)
{
    EmployeeMapper em = session.getMapper(EmployeeMapper.class);
    HashMap<String, Object> params = new HashMap<String, Object>();
    // 设置loginname 和password属性
    params.put("loginname", "jack");
    params.put("password", "1245");
    List<Employee> list = em.selectEmployeeByLoginlike(param);
    list.forEach(employee -> System.out.println(employee));
}

运行上面的main方法,测试selectEmployeeByLoginLike方法,控制台显示如下:

DBBUG [main]==> Preparing: SBLECT * EROM tb_employee WHERE state = 'ACTIVE' and loginname = ? and password = ?
DEBUG [main]==> Parameters: jack(String),123456(String)
DEBUG [main]==> Total :1
Employee [id=1,loginname=jack,password=123456,name=马云,sex=男,age=26,phone=13900000001,sal=9800.0,state=ACTIVE]

可以看到,执行的sql语句中因为传入了loginname和password属性,故sql语句中包含了"and loginname = ? and password = ? ",查询返回的Emplyee对象就是logimame,即jack,并且password是123456的对象。

insert 新增 中使用<if>标签:

通过判断参数值是否为空来决定是否将SQL字段和对象加入到SQL语句中:

<mapper namespace="cn.mybatis.mapper.EmployeeMapper">
  <insert id="insertEmployee" useGeneratedKeys="true" keyProperty="id">
    insert into tb_employee (
    <if test="loginname != null and loginname != ''">
        loginname,
    </if>
    <if test="password != null and password != ''">
        password,
    </if>
    <if test="name != null and name != ''">
        name,
    </if>
    status ) values (
    <if test="loginname != null and loginname != ''">
        #{loginname},
    </if>
    <if test="password != null and password != ''">
        #{password},
    </if>
    <if test="name != null and name != ''">
        #{name},
    </if>
    #{status}
    )
  </insert>
</mapper>

update修改中使用 if 标签

通过判断参数值是否为空来决定是否将SQL字段和对象加入到SQL语句中:

<mapper namespace="cn.mybatis.mapper.EmployeeMapper">
<update id="updateEmployee">
        update tb_employee
        <set>
            <if test="loginname != null and loginname !=''">
                loginname = #{loginname},
            </if>
            <if test="password != null and password != ''">
                password = #{password},
            </if>
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="status != null and status != ''">
                status = #{status},
            </if>
            id = #{id} where id = #{id}
        </set>
    </update>
</mapper>

标签: none

添加新评论