mybatis3学习笔记(五)之高级查询

本文介绍如何在MyBatis中使用动态SQL进行模糊查询和条件筛选,并提供了一个具体的测试案例。
1.修改StudentMapper.xml文件,增加动态sql语句映射
<!-- 动态sql -->
 <select id="dymSelectStudent"  resultMap="studentResultMap">
select * from student
<where>
<!-- 模糊查询 -->
<!-- mysql -->
<if test="name != null">
and stu_name like concat('%',#{name},'%')
</if>
<!-- sqlserver
<if test="name != null">
and stu_name like '%'+#{name}+'%'
</if>
-->
<!-- oracle
<if test="name != null">
and stu_name like '%'||#{name}||'%'
</if>
-->
<choose>
<when test="code=='001'">
and stu_code = '001'
</when>
<when test="code=='002'">
and stu_code = '002'
</when>
<otherwise>
and stu_code = #{code}
</otherwise>
</choose>

<if test="list!=null">
and id in
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</if>
order by ${orderName}
</where>
</select>
2.增加测试用例
@Test
public void dymSelectStudentTest(){
SqlSession session = sessionFactory.openSession();
try{
HashMap<String,Object> map = new HashMap<String, Object>();
List<Long> ids = new ArrayList<Long>();
ids.add(9L);
ids.add(10L);
map.put("code", "005");
map.put("name", "hel");
map.put("list", ids);
map.put("orderName", "id");
List<Student> studentList = (List<Student>)session.selectList("com.mybatis.mapper.StudentMapper.dymSelectStudent", map);
for(Student s : studentList)
System.out.println("name:"+s.getName());
}catch(Exception e){
e.printStackTrace();
}finally{
session.close();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值