mybatis使用foreach遍历list集合或者array数组方式
短信预约 -IT技能 免费直播动态提醒
一、准备工作
1.db.properties文件(记得修改自己的数据库和用户名、密码)
dataSource.driver=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
dataSource.username=blog
dataSource.password=blog
2.主配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 引入外部配置文件-->
<properties resource="db.properties"></properties>
<!-- 别名设置,不设置时引用要使用全包名,设置后可以使用自定义别名,更加简洁 -->
<typeAliases>
<!-- 别名设置有两种,一种是一个一个设置,另外一种是设置某个包,默认别名为类名(大小写都可以,建议小写) -->
<!-- 第一种设置
<typeAlias type="com.mybatis_demo.domain.User" alias="user"/>-->
<!-- 第二种设置,整个包下面的类都进行别名设置,推荐第二种 -->
<package name="com.mybatis_demo.domain"/>
</typeAliases>
<!-- 环境模式:development开发模式 work工作模式 -->
<environments default="development">
<!-- 环境变量 -->
<environment id="development">
<!-- 使用jdbc的事务管理 -->
<transactionManager type="JDBC"/>
<!-- 使用连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${dataSource.driver}"/>
<property name="url" value="${dataSource.url}"/>
<property name="username" value="${dataSource.username}"/>
<property name="password" value="${dataSource.password}"/>
</dataSource>
</environment>
</environments>
<!-- 引入mapper映射文件 -->
<mappers>
<!-- 1.相对路径引入-->
<!-- <mapper resource="mapper/UserMapper.xml"/> -->
<!-- 2.绝对路径引入 -->
<!-- <mapper url="file:\\\D:\sts-bundle\workplace\mybatis_demo\class="lazy" data-src\main\resources\mapper\UserMapper.xml"/> -->
<!-- 3.对应mapper接口全包名引入,需要对应的mapper.xml与接口mapper处于同一包下才可以,且xml文件名与接口名要相同,xml文件中的namespace必须是对应接口的全包名 -->
<!-- <mapper class="com.mybatis_demo.mapper.UserMapper"/> -->
<!-- 4.包引入,要求跟接口引入一样 -->
<!-- <mapper resource="mapper/UserMapper2.xml"/> -->
<package name="com.mybatis_demo.mapper"/>
</mappers>
</configuration>
3.创建User类和包装类UserVo
User.java
package com.mybatis_demo.domain;
public class User {
private Integer uid;
private String uname;
private Integer age;
private String address;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [uid=" + uid + ", uname=" + uname + ", age=" + age + ", address=" + address + "]";
}
}
UserVo.java
package com.mybatis_demo.domain;
import java.util.List;
public class UserVo extends User {
private Integer[] ids;
private List<Integer> idList;
public Integer[] getIds() {
return ids;
}
public void setIds(Integer[] ids) {
this.ids = ids;
}
public List<Integer> getIdList() {
return idList;
}
public void setIdList(List<Integer> idList) {
this.idList = idList;
}
}
二、遍历数组和集合的映射文件和对应的接口
1.mapper映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis_demo.mapper.UserMapper">
<!-- 遍历list集合,collection="list",如果你传参的时候是直接传递list集合,那么这里只能填list,不能填参数名 -->
<select id="selectByList" resultType="User">
select * from t_user where uid in
<foreach collection="list" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
<!-- 遍历数组 ,collection="array",如果你传参的时候是直接传递数组,那么这里只能填array,不能填参数名-->
<select id="selectByArray" resultType="User">
select * from t_user where uid in
<foreach collection="array" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
<!-- 遍历包装类中的数组,collection="ids",这里不再是array,而是包装类中对应的变量名,因为你传递的参数是一个包装类,mybatis是通过get方法获取包装类中的数组 -->
<select id="selectUserVoByArray" parameterType="UserVo" resultType="User">
select * from t_user where uid in
<foreach collection="ids" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
<!-- 遍历包装类中的list集合,collection="idList",这里不再是list,而是包装类中对应的变量名,因为你传递的参数是一个包装类,mybatis是通过get方法获取包装类中的list集合 -->
<select id="selectUserVoByList" parameterType="UserVo" resultType="User">
select * from t_user where uid in
<foreach collection="idList" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
</mapper>
2.mapper接口
UserMapper.interface
package com.mybatis_demo.mapper;
import java.util.List;
import java.util.Map;
import com.mybatis_demo.domain.User;
import com.mybatis_demo.domain.UserVo;
public interface UserMapper {
//mybatis使用mapper动态代理
//4大原则,一个注意
//1.接口中的方法名需要与对应mapper.xml的id一致
//2.接口中的返回值需要与对应mapper.xml的返回值类型保持一致
//3.接口中的参数需要与对应mapper.xml的参数类型、个数、参数名保持一致
//4.对应mapper.xml的名字空间需要修改成对应接口的全包名
//注意:mapper动态代理根据返回值类型,mybatis会自动选择调用selectone还是selectlist....
//用list封装条件
public List<User> selectByList(List<Integer> testlist);
//用数组封装条件
public List<User> selectByArray(Integer[] ids);
//用包装类中的数组封装条件
public List<User> selectUserVoByArray(UserVo userVo);
//用包装类中的list封装条件
public List<User> selectUserVoByList(UserVo userVo);
}
三、测试代码
package com.mybatis_demo.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.mybatis_demo.domain.User;
import com.mybatis_demo.domain.UserVo;
import com.mybatis_demo.mapper.UserMapper;
public class TestMapper {
//用包装类中的list封装条件,传递参数是一个包装类
@Test
public void test_selectUserVoByList() {
try {
//读取配置文件
InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
//创建SqlSessionFactoryBuilder对象,用来获取SqlSessionFactory对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//利用SqlSessionFactoryBuilder对象build一个SqlSessionFactory对象
SqlSessionFactory build = builder.build(in);
//利用sqlSessionFactory获取session对象
SqlSession session = build.openSession();
//通过session对象获取对应mapper接口
UserMapper mapper = session.getMapper(UserMapper.class);
List<Integer> idList = new ArrayList<Integer>();
idList.add(5);
idList.add(3);
idList.add(123);
idList.add(19);
UserVo userVo = new UserVo();
userVo.setIdList(idList);
List<User> users = mapper.selectUserVoByList(userVo);
for (User user : users) {
System.out.println(user);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//用包装类中的array封装条件,传递参数是一个包装类
@Test
public void test_selectUserVoByArray() {
try {
//读取配置文件
InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
//创建SqlSessionFactoryBuilder对象,用来获取SqlSessionFactory对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//利用SqlSessionFactoryBuilder对象build一个SqlSessionFactory对象
SqlSessionFactory build = builder.build(in);
//利用sqlSessionFactory获取session对象
SqlSession session = build.openSession();
//通过session对象获取对应mapper接口
UserMapper mapper = session.getMapper(UserMapper.class);
Integer[] ids = new Integer[]{5,9,30};
UserVo userVo = new UserVo();
userVo.setIds(ids);
List<User> users = mapper.selectUserVoByArray(userVo);
for (User user : users) {
System.out.println(user);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//用数组封装条件,传递参数是一个数组
@Test
public void test_selectByArray() {
try {
//读取配置文件
InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
//创建SqlSessionFactoryBuilder对象,用来获取SqlSessionFactory对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//利用SqlSessionFactoryBuilder对象build一个SqlSessionFactory对象
SqlSessionFactory build = builder.build(in);
//利用sqlSessionFactory获取session对象
SqlSession session = build.openSession();
//通过session对象获取对应mapper接口
UserMapper mapper = session.getMapper(UserMapper.class);
Integer[] ids = new Integer[]{5,9,30};
List<User> users = mapper.selectByArray(ids);
for (User user : users) {
System.out.println(user);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//用list封装条件,传递参数是一个list集合
@Test
public void test_selectByList() {
try {
//读取配置文件
InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
//创建SqlSessionFactoryBuilder对象,用来获取SqlSessionFactory对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//利用SqlSessionFactoryBuilder对象build一个SqlSessionFactory对象
SqlSessionFactory build = builder.build(in);
//利用sqlSessionFactory获取session对象
SqlSession session = build.openSession();
//通过session对象获取对应mapper接口
UserMapper mapper = session.getMapper(UserMapper.class);
List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(3);
list.add(123);
list.add(19);
List<User> users = mapper.selectByList(list);
for (User user : users) {
System.out.println(user);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
四、总结
1.如果你传参的时候直接传一个数组,那么使用foreach遍历时collection=“array”,这里是固定写法,即这里的array与你的实参名无关
2.如果你传参的时候直接传一list集合,那么使用foreach遍历时collection=“list”,这里是固定写法,即这里的list与你的实参名无关
3.如果你传参的时候直接传一个含有数组成员变量的类,那么使用foreach遍历时collection=“你的变量名”,这里不再是固定写法,即这里的命名取决于成员变量的变量名,例如:成员变量名是test,那么就是collection=“test”
4.如果你传参的时候直接传一个含有list集合成员变量的类,跟3的情况一样
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341