if + where 用法

  1. if 元素来实现多条件查询

    1.1 UserMapper.xml配置文件

  <!--查询用户列表 (if)-->
<select id="getUserList2" resultType="User">
select u.*,r.roleName from smbms_user u,smbms_role r where u.userRole = r.id
<if test="null != userRole">
and u.userRole = #{userRole}
</if> <if test="null != userName and '' != userName">
and u.userName like CONCAT ('%',#{userName},'%')
</if>
</select>

    1.2UserMapper接口

  /**
* 以@Param注解传入参数查询
* @param userName
* @param roleId
* @return
*/
public List<User> getUserList2(@Param("userName")String userName,
@Param("userRole")Integer roleId);

    1.3测试方法

  /**
* 以@Param注解传入参数查询
*/
@Test
public void getUserList(){
List<User> users = new ArrayList<User>();
sqlSession = MyBatisUtil.createSqlSession();
String userName = "孙";
// Integer roleId = 3;
Integer roleId = null;
users = sqlSession.getMapper(UserMapper.class).getUserList2(userName,roleId); for(User u: users){
logger.debug("testGetUserList userCode: " + u.getUserCode() +
" and userName: " + u.getUserName() +
" and userRole: " + u.getUserRole() +
// " and userRoleName: " + u.getUserRoleName() +
" and age: " + u.getAge() +
" and address: " + u.getAddress());
}
}

  2. where

    2.1 UserMapper.xml配置文件

  <!--查询用户列表 (if + where) where 会自动拼接and 和 or-->
<select id="getUserList2" resultType="User">
select * from smbms_user
<where>
<if test="userName != null and userName != ''">
and userName like CONCAT ('%',#{userName},'%')
</if>
<if test="userRole != null">
and userRole = #{userRole}
</if>
</where>
</select>

    2.2 UserMapper接口

  /**
* 以@Param注解传入参数查询
* @param userName
* @param roleId
* @return
*/
public List<User> getUserList2(@Param("userName")String userName,
@Param("userRole")Integer roleId);

    2.3 测试方法

  /**
* 以@Param注解传入参数查询
*/
@Test
public void getUserList(){
List<User> users = new ArrayList<User>();
sqlSession = MyBatisUtil.createSqlSession();
String userName = "";
Integer roleId = 3;
users = sqlSession.getMapper(UserMapper.class).getUserList2(userName,roleId); logger.debug("userlist.size ----> " + users.size());
for(User u: users){
logger.debug("testGetUserList userCode: " + u.getUserCode() +
" and userName: " + u.getUserName() +
" and userRole: " + u.getUserRole() +
" and userRoleName: " + u.getUserRoleName() +
" and age: " + u.getAge() +
" and address: " + u.getAddress());
}
}

使用动态SQL语句if来查询操作

  1. BillMapper.xml配置文件

  <!--根据多参条件查询订单表-->
<select id="getBillList2" resultMap="billList">
SELECT p.`id` as p_id,b.`billCode`,b.`productName`,p.`proCode`,p.`proName`,p.`proContact`,p.`proPhone`,b.`totalPrice`,b.`isPayment`
FROM smbms_bill b,smbms_provider p
WHERE b.providerId = p.id
<if test="productName != null and productName != ''">
and b.`productName` like concat('%', #{productName} ,'%')
</if>
<if test="providerId != null">
and b.providerId = #{providerId}
</if>
<if test="isPayment != null">
and b.isPayment = #{isPayment}
</if>
</select>

  2. BillMapper接口

  /**
* 根据条件查询订单
* @param productName
* @param providerId
* @param isPayment
* @return
*/
public List<Bill> getBillList2(@Param("productName")String productName,
@Param("providerId")Integer providerId,
@Param("isPayment")Integer isPayment);

  3. 测试方法

  private Logger logger = Logger.getLogger(BillMapperTest.class);

    /**
* 根据多参条件查询订单表
*/
@Test
public void testGetBillList2(){
SqlSession session1 = null;
List<Bill> bills = new ArrayList<Bill>();
try {
session1 = MyBatisUtil.createSqlSession();
String productName = "油";
Integer providerId = 7;
Integer isPayment = 2;
bills = session1.getMapper(BillMapper.class).getBillList2(productName, providerId, isPayment);
} catch (Exception e) {
e.printStackTrace();
} finally {
MyBatisUtil.closeSqlSession(session1);
}
for (Bill bill : bills){
logger.debug("testGetBillList id: " + bill.getId() +
" and BillCode: " + bill.getBillCode() +
" and ProductName: " + bill.getProductName() +
" and totalPrice: " + bill.getTotalPrice() +
" and isPayment: " + bill.getIsPayment() +
" , Provider : " + bill.getProvider().getId() +
" and providerCode: " + bill.getProvider().getProCode() +
" and providerName: " + bill.getProvider().getProName()+
" and proContact: " + bill.getProvider().getProContact()+
" and proPhone:" + bill.getProvider().getProPhone());
} }

使用动态SQL if +where

  1. ProviderMapper.xml配置文件

  <!-- 查询供应商列表 -->
<select id="getProviderList" resultType="Provider">
select * from smbms_provider
<where>
<if test="proCode != null and proCode != ''">
and proCode like CONCAT ('%',#{proCode},'%')
</if>
<if test="proName != null and proName != ''">
and proName like CONCAT ('%',#{proName},'%')
</if>
</where>
</select>

  2. ProviderMapper接口

  /**
* 根据供应商编号或名称查询供应商列表(模糊查询)
*/
public List<Provider> getProviderList(@Param("proCode")String proCode,
@Param("proName")String proName);

  3. 测试方法

  //模糊查询商品列表
@Test
public void testGetProviderListByProviderName(){
List<Provider> providers = new ArrayList<Provider>();
session = MyBatisUtil.createSqlSession();
String proCode = "BJ";
String proName = null; providers = session.getMapper(ProviderMapper.class).getProviderList(proCode,proName);
for (Provider provider : providers){
logger.debug("testGetProviderList id: " + provider.getId() +
" and proCode: " + provider.getProCode() +
" and proName: " + provider.getProName()+
" and proPhone: " + provider.getProPhone()+
" and proContact: " + provider.getProContact()+
" and proFax: " + provider.getProFax()+
" and creationDate: " + new SimpleDateFormat("yyyy-MM-dd").format(provider.getCreationDate()));
}
}

if + trim 用法 比where 更强

  1. UserMapper.xml配置文件

  <!--查询用户列表 (if + trim)-->
<select id="getUserList2" resultType="User">
select * from smbms_user
<trim prefix="where" prefixOverrides="and | or">
<if test="userName != null and userName != ''">
and userName like CONCAT ('%',#{userName},'%')
</if>
<if test="userRole != null">
and userRole = #{userRole}
</if>
</trim>
</select>

  2. UserMapper接口

  /**
* 以@Param注解传入参数查询
* @param userName
* @param roleId
* @return
*/
public List<User> getUserList2(@Param("userName")String userName,
@Param("userRole")Integer roleId);

  3. 测试方法

  /**
* 以@Param注解传入参数查询
*/
@Test
public void getUserList(){
List<User> users = new ArrayList<User>();
sqlSession = MyBatisUtil.createSqlSession();
String userName = "孙";
Integer roleId = 3;
users = sqlSession.getMapper(UserMapper.class).getUserList2(userName,roleId); logger.debug("userlist.size ----> " + users.size());
for(User u: users){
logger.debug("testGetUserList userCode: " + u.getUserCode() +
" and userName: " + u.getUserName() +
" and userRole: " + u.getUserRole() +
" and userRoleName: " + u.getUserRoleName() +
" and age: " + u.getAge() +
" and address: " + u.getAddress());
}
}

if + set 用法 更新操作

  1. UserMapper.xml配置文件

  <!--修改用户信息-->
<update id="modify" parameterType="User">
update smbms_user
<set>
<if test="userCode != null">userCode = #{userCode},</if>
<if test="userName != null">userName=#{userName},</if>
<if test="userPassword != null">userPassword=#{userPassword},</if>
<if test="gender != null">gender=#{gender},</if>
<if test="birthday != null">birthday=#{birthday},</if>
<if test="phone != null">phone=#{phone},</if>
<if test="address != null">address=#{address},</if>
<if test="userRole != null">userRole=#{userRole},</if>
<if test="modifyBy != null">modifyBy=#{modifyBy},</if>
<if test="modifyDate != null">modifyDate=#{modifyDate}</if>
</set>
where id = #{id}
</update>

  2. UserMapper接口

  /**
* 修改用户
* @param user
* @return
*/
public int modify(User user);

  3. 测试方法

  //修改用户
@Test
public void testModify() throws ParseException {
int count = 0;
User user = new User();
user.setId(19);
user.setUserCode("testmodify");
user.setUserName("测试用户修改");
user.setUserPassword("0000000");
Date birthday = new SimpleDateFormat("yyyy-MM-dd").parse("1980-10-10");
user.setBirthday(birthday);
user.setCreationDate(new Date());
user.setAddress("地址测试修改");
user.setGender(2);
user.setPhone("13600002222");
user.setUserRole(2);
user.setModifyBy(1);
user.setModifyDate(new Date());
sqlSession = MyBatisUtil.createSqlSession();
count = sqlSession.getMapper(UserMapper.class).modify(user);
logger.debug("testModify count: " + count);
}

 使用动态SQL语句 if + set 修改操作

  1. ProviderMapper.xml配置文件

  <!--根据供应商ID修改供应商信息-->
<update id="updateProvider" parameterType="Provider">
update smbms_provider
<set>
<if test="proName != null">proName = #{proName}</if>
</set>
where id = #{id}
</update>

  2. ProviderMapper接口

  /**
* 根据供应商ID修改供应商
* @param provider
* @return
*/
public int updateProvider(Provider provider);

  3. 测试方法

   /**
* 根据ID修改供应商
*/
@Test
public void updateProvider(){
session = MyBatisUtil.createSqlSession();
Provider provider = new Provider();
provider.setId(15);
provider.setProName("供应商");
int count = session.getMapper(ProviderMapper.class).updateProvider(provider); logger.debug(count);
}

 使用动态SQL语句 if + trim 修改操作 等同于 if + set

  1. ProviderMapper.xml配置文件

  <!-- 修改供应商信息 -->
<update id="modify" parameterType="Provider">
update smbms_provider
<trim prefix="set" suffixOverrides="," suffix="where id = #{id}">
<if test="proCode != null">proCode=#{proCode},</if>
<if test="proName != null">proName=#{proName},</if>
<if test="proDesc != null">proDesc=#{proDesc},</if>
<if test="proContact != null">proContact=#{proContact},</if>
<if test="proPhone != null">proPhone=#{proPhone},</if>
<if test="proAddress != null">proAddress=#{proAddress},</if>
<if test="proFax != null">proFax=#{proFax},</if>
<if test="modifyBy != null">modifyBy=#{modifyBy},</if>
<if test="modifyDate != null">modifyDate=#{modifyDate},</if>
</trim>
</update>

  2. ProviderMapper接口

  /**
* 修改供应商信息
* @param provider
* @return
*/
public int modify(Provider provider);

  3. 测试方法

  /**
* 修改供应商
*/
@Test
public void updateProvider(){
session = MyBatisUtil.createSqlSession();
Provider provider = new Provider();
provider.setId(15);
//provider.setProCode("BJ_GYS123");
//provider.setProName("供应商测试修改");
provider.setProContact("张扬");
provider.setProAddress("供应商测试地址修改");
//provider.setProPhone("13500002222");
provider.setModifyBy(1);
provider.setModifyDate(new Date());
//provider.setProFax("010-588876565");
//provider.setProDesc("供应商测试描述修改");
int count = session.getMapper(ProviderMapper.class).modify(provider); logger.debug(count);
}

Mybatis(三) 动态SQL的更多相关文章

  1. MyBatis的动态SQL详解

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑,本文详解mybatis的动态sql,需要的朋友可以参考下 MyBatis 的一个强大的特性之一通常是它 ...

  2. MyBatis框架——动态SQL、缓存机制、逆向工程

    MyBatis框架--动态SQL.缓存机制.逆向工程 一.Dynamic SQL 为什么需要动态SQL?有时候需要根据实际传入的参数来动态的拼接SQL语句.最常用的就是:where和if标签 1.参考 ...

  3. 使用Mybatis实现动态SQL(一)

    使用Mybatis实现动态SQL 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 写在前面:        *本章节适合有Mybatis基础者观看* 前置讲解 我现在写一个查询全部的 ...

  4. mybatis中的.xml文件总结——mybatis的动态sql

    resultMap resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功. 如果sql查询字段名和pojo的属性名不一致,可以通过re ...

  5. MyBatis的动态SQL详解-各种标签使用

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑. MyBatis中用于实现动态SQL的元素主要有: if choose(when,otherwise) ...

  6. 一分钟带你了解下MyBatis的动态SQL!

    MyBatis的强大特性之一便是它的动态SQL,以前拼接的时候需要注意的空格.列表最后的逗号等,现在都可以不用手动处理了,MyBatis采用功能强大的基于OGNL的表达式来实现,下面主要介绍下. 一. ...

  7. 使用Mybatis实现动态SQL(二)

    使用Mybatis实现动态SQL 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 写在前面:        *本章节适合有Mybatis基础者观看* 使用Mybatis实现动态SQL ...

  8. Mybatis解析动态sql原理分析

    前言 废话不多说,直接进入文章. 我们在使用mybatis的时候,会在xml中编写sql语句. 比如这段动态sql代码: <update id="update" parame ...

  9. mybatis 使用动态SQL

    RoleMapper.java public interface RoleMapper { public void add(Role role); public void update(Role ro ...

随机推荐

  1. 妙味课堂——JavaScript基础课程笔记

    集中时间把秒微课堂JS的基础课程看完,并且认真完成了课后练习.感觉在JS方面的技能算是入了个门了.课后练习的作业完成的代码我都汇总在了这里.至于视频课的学习笔记,则记录如下. 第01课JS入门基础_热 ...

  2. Codeforces Gym Joyride(分层图,dijkstra)

    题意:有一张图,每条边有一个边权t表示经过所花时间,每个点有两个权t.p,分别表示经过该点所花时间和所花费用,要求找一条路径,从点1出发再回到点1,所花时间恰好为x且费用最小,输出其费用,找不到则输出 ...

  3. [CSP-S模拟测试]:A(数学)

    题目传送门(内部题44) 输入格式 一行四个整数,分别表示$S,T,a,b$. 输出格式 输出最小步数,数据保证有解. 样例 样例输入: 10 28 4 2 样例输出: 数据范围与提示 样例解释: 先 ...

  4. linux 上修改了nginx.conf 怎么重新加载配置文件生效

    步骤如下先利用/usr/local/nginx/sbin/nginx -t测试配置文件修改是否正常/usr/local/nginx/sbin/nginx -s reload重新加载 nginx 更改配 ...

  5. 解决Maven打包提示:读取C:\Users\Administrator\.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar时出错; invalid LOC header (bad signature)

    1.打包情况 虽然提示读取jar包出错,但是还是能打包成功,在执行打的jar包时会报错,说找不到相关的类. 2.解决方案 从提示的路径可以找到对应的jar包,但为什么会读取错误呢?尝试着双击打开log ...

  6. 关于MongoDB在windows下安装【解压版】

    一.首先创建数据库存储文件夹和日志文件夹,在mongodb下创建即可,找起来也方便,日志文件:mongo.log,安装出错方便查阅问题: 二.启动MongoDB服务:注意:一定要用管理员身份运行DOS ...

  7. zookeeper系列(八)zookeeper客户端的底层详解

    作者:leesf    掌控之中,才会成功:掌控之外,注定失败.出处:http://www.cnblogs.com/leesf456/p/6098255.html 尊重原创,共同学习进步:  一.前言 ...

  8. 黑马lavarel教程---5、模型操作(AR模式)

    黑马lavarel教程---5.模型操作(AR模式) 一.总结 一句话总结: AR: ActiveRecord :Active Record(活动记录),是一种领域模型模式,特点是一个模型类对应关系型 ...

  9. Nginx开启访问日志记录

    1. vi /etc/nginx/nginx.conf 2.打开 log_format 前的注释 3.Server节点中加入 access_log logs/www_access.log main; ...

  10. golang mysql 如何设置最大连接数和最大空闲连接数

    本文介绍golang 中连接MySQL时,如何设置最大连接数和最大空闲连接数. 关于最大连接数和最大空闲连接数,是定义在golang标准库中database/sql的. 文中例子连接MySQL用的SQ ...