idea中基于mybatis下的条件查询与动态条件查询

本文介绍了在IntelliJ IDEA中使用MyBatis进行条件查询的方法,包括散装条件、封装对象和封装Map集合三种方式,并讨论了如何处理用户输入的模糊查询。同时,文章详细讲解了MyBatis的动态SQL查询功能,如if和where标签,以及choose、when标签的使用,以应对用户只提供部分查询条件时的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

条件查询

①多条件查询三种方式

a.散装条件查询:(@Param("sql占位符的名称")参数类型 参数值)

b.封装对象查询:对象的属性名必须与sql占位符的名称一致

c.封装map集合查询:键值和sql占位符的名称一致

示例:

 

public interface BrandMapper {
//1、散装条件
List<Brand> selectByCondition(@Param("id")int id,@Param("name") 
	String name,@Param("businessName")String bussinessName);
//2、封装对象
List<Brand> selectByCondition(Brand brand);
//3、封装map集合
List<Brand> selectByCondition(Map map);
}

BrandMapper.xml中的select语句

<select id="selectByCondition" resultMap="resultBrandMap">
    select * from brand where
    id=#{id}
    and name like #{name}
    and businessname like #{businessName}
</select>

因为是like是模糊查找在对用户输入的字段需要添加"%",这个根据实际需要进行处理

例如:

String name="神州";
String businessName="神州";
//处理参数
name="%"+name+"%";
businessName="%"+businessName+"%";

②动态条件查询

上述条件查询存在一个问题就是当用户只提供一个查询条件时,会查询失败,所以需要动态查询
mybatis中提供了很强大的动态sql查询功能
*if,where标签
*choose(相当于switch),when(相当于case)

BrandMapper.xml中的select语句变为

<!--动态多条件查询-->
<selectid="selectByCondition"resultMap="resultBrandMap">
    select *
    from brand
    <where>
          <if test="id !=null">
               and id = #{id}
          </if>
          <if test="name!= null and name!='' ">
              and name like #{name}
          </if>
      <if test="businessName!= null and businessName!=''">
          and businessname like #{businessName}
      </if>
    </where>
</select>

<!--动态单条件查询-->
<select id="selectByCondition" resultMap="resultBrandMap">
        select *
        from brand
        <where>
            <choose>
                <when test="id !=null">
                    id = #{id}
                </when>
                <when test="name!= null and name!=''">
                    name like #{name}
                </when>
                <when test="businessName!= null and businessName!=''">
                    businessname like #{businessName}
                </when>
                <otherwise>/*相当于default,在where标签内可以不用写*/
                    1=1
                </otherwise>
            </choose>
        </where>
    </select>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值