条件查询
①多条件查询三种方式
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>