【MyBatis框架】mapper配置文件-foreach标签
foreach标签
下面介绍一下一个mapper配置文件中的foreach标签(注意,要跟着前面的总结来看,这里使用的例子是结合前面的工程写的,大部分代码没有再赘述)
foreach的作用是向sql传递数组或List,mybatis使用foreach解析
1.1需求
在用户查询列表和查询总数的statement中增加多个id输入查询。
sql语句如下:
两种方法:
SELECT * FROM USER WHERE id=1 OR id=3 OR id=5
SELECT * FROM USER WHERE id IN(1,3,5)
1.2在输入参数类型中添加List
public class UserQueryVo {
//传入多个id
private List
public List
return ids;
}
public void setIds(List
this.ids = ids;
}
……
}
1.3修改mapper.xml
WHERE id=1 OR id=3 OR id=5
在查询条件中,查询条件定义成一个sql片段,需要修改sql片段。
[html] view plain copy
- <**pre name=”code” class=”html”>**<!— 定义sql片段
- id:sql片段的唯一标识
- 在sql片段中不要加入where
- 经验:一般我们定义sql片段是为了可重用性,是基于单表来定义sql片段,
- 这样的话这个sql片段可重用性才高—>
- <**sql id=”query_user_where”>**
- <**if test=”ids!=null”>**
- <!— 使用foreach遍历传入ids
- collection指定输入对象中集合属性
- item每次遍历生成的对象名
- open开始遍历时要拼接的串
- close开始遍历时要拼接的串
- separator遍历的两个对象中间需要拼接的串
- —>
- <!— 使用实现下边的sql拼接
- WHERE (id=1 OR id=3 OR id=5)—>
- <**foreach collection=”ids” item=”user_id” open=”AND (“ close=”)” separator=”OR”>**
- id=#{user_id}
- </**foreach**>
- </**if**>
- </**sql**>
- <**select** id=”findUserList” parameterType=”cn.edu.hpu.mybatis.PO.UserQueryVo”
- resultType=”cn.edu.hpu.mybatis.PO.UserCustom”>
- select * from user
- <**where**>
- <**include refid=”query_user_where”></include**>
- </**where**>
- </**select**>
在mapper接口类中添加相应方法:
[java] view plain copy
- //用户管理的Dao接口
- public interface UserMapper {
- //用户信息综合查询
- public List
findUserList(UserQueryVo userQueryVo) throws Exception; - ……
- }
1.4测试代码
[java] view plain copy
- //用户信息综合查询
- @Test
- public void testFindUserList() throws Exception{
- SqlSession sqlSession=sqlSessionFactory.openSession();
- //创建UserMapper代理对象
- UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
- //创建包装对象,设置查询条件
- UserQueryVo userQueryVo=new UserQueryVo();
- //传入多个Id
- List
ids=new ArrayList (); - ids.add(1);
- ids.add(3);
- ids.add(5);
- //将ids通过userQueryVo传入statement中
- userQueryVo.setIds(ids);
- //调用userMapper的方法
- List
users=userMapper.findUserList(userQueryVo); - for (int i = 0; i < users.size(); i++) {
- UserCustom user=(UserCustom)users.get(i);
- System.out.println(user.getId()+”:”+user.getUsername());
- }
- }
测试结果:
1:张三
3:刘莉莉
5:刘三姐
日志输出:
[plain] view plain copy
- DEBUG [main] - Opening JDBC Connection
- DEBUG [main] - Created connection 6867819.
- DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.Connection@68cb6b]
- DEBUG [main] - ==> Preparing: select * from user WHERE ( id=? OR id=? OR id=? )
- DEBUG [main] - ==> Parameters: 1(Integer), 3(Integer), 5(Integer)
- DEBUG [main] - <== Total: 3
可以看到,sql语句select * from user WHERE ( id=? OR id=? OR id=? ) 通过foreach输出成功
1.5另外一个sql的实现:
[html] view plain copy
- <!— 使用实现下边的sql拼接
- AND ID IN(1,3,5)—>
- <**foreach collection=”ids” item=”user_id” open=”AND ID IN(“ close=”)” separator=”,”>**
- #{user_id}
- </**foreach**>
还没有评论,来说两句吧...