mybatis uses foreach to iterate through list collections or array s

Keywords: Session xml Java Mybatis

I. Preparations

1.db.properties file (remember to modify your database and user name, password)

dataSource.driver=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
dataSource.username=blog
dataSource.password=blog

2. Main Profile

<?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>
<!--  Introducing external profiles-->
	<properties resource="db.properties"></properties>
	<!-- Alias settings, refer to use full package name when not set, can use custom aliases after setting, more concise -->
	<typeAliases>
		<!-- There are two kinds of alias settings, one is a setting, the other is to set a package, the default alias is the class name (case is fine, lower case is recommended) -->
		<!-- First setting 
	 	<typeAlias type="com.mybatis_demo.domain.User" alias="user"/>-->
	 	<!-- The second is an alias setting for all classes below the package, the second is recommended -->
	 	<package name="com.mybatis_demo.domain"/>
	 </typeAliases>
<!-- Environment mode: development Development Mode work Working mode -->
  <environments default="development">
  <!-- environment variable -->
    <environment id="development">
    <!-- Use jdbc Transaction Management -->
      <transactionManager type="JDBC"/>
      <!-- Use connection pool -->
      <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>
  <!-- Introduce mapper Mapping File -->
  <mappers>
  <!--  1.Relative path introduction-->
   <!--  <mapper resource="mapper/UserMapper.xml"/> -->
    <!-- 2.Absolute path introduction -->
    <!-- <mapper url="file:\\\D:\sts-bundle\workplace\mybatis_demo\src\main\resources\mapper\UserMapper.xml"/> -->
    <!-- 3.Corresponding mapper Interface full package name introduced, need corresponding mapper.xml And interface mapper Under the same package, and xml The file name should be the same as the interface name. xml In the file namespace Must be the full package name of the corresponding interface -->
    <!-- <mapper class="com.mybatis_demo.mapper.UserMapper"/> -->
    <!-- 4.Package introduction, as required by interface introduction -->
   <!--  <mapper resource="mapper/UserMapper2.xml"/> -->
    <package name="com.mybatis_demo.mapper"/>
  </mappers>
</configuration>

3. Create User Class and Packaging Class 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;
	}
	
}

2. Mapping files and corresponding interfaces for traversing arrays and collections

1.mapper map file

<?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">
<!-- ergodic list Collection, collection="list",If you pass a parameter directly list Set, then only fill in here list,Cannot fill in parameter name -->
<select id="selectByList" resultType="User">
	select * from t_user where uid in
	<foreach collection="list" item="item" open="(" separator="," close=")">
		#{item}
	</foreach>
</select>
<!-- Traversing through the array, collection="array",If you pass an array directly when you pass it, you can only fill it in here array,Cannot fill in parameter name-->
<select id="selectByArray" resultType="User">
	select * from t_user where uid in
	<foreach collection="array" item="item" open="(" separator="," close=")">
		#{item}
	</foreach>
</select>
<!-- Traversing through the array in the wrapper class, collection="ids",Not here anymore array,Instead, it's the variable name in the wrapper class, because the parameter you pass is a wrapper class. mybatis Is through get Method to get an array in a wrapper class -->
<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>
<!-- Traversing through wrapper classes list Collection, collection="idList",Not here anymore list,Instead, it's the variable name in the wrapper class, because the parameter you pass is a wrapper class. mybatis Is through get Method to get the list aggregate -->
<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 interface

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 uses mapper dynamic proxy
	
	//Four principles, one note
	//1. The method name in the interface needs to match the id of the corresponding mapper.xml
	//2. The return value in the interface needs to be consistent with the return value type of the corresponding mapper.xml
	//3. Parameters in the interface need to be consistent with the corresponding mapper.xml parameter type, number, parameter name
	//4. The corresponding mapper.xml namespace needs to be modified to the full package name of the corresponding interface
	//Note: The mapper dynamic proxy automatically chooses to call selectone or selectlist... depending on the return value type.

	//Encapsulate conditions with list
	public List<User> selectByList(List<Integer> testlist);
	//Encapsulating conditions with arrays
	public List<User> selectByArray(Integer[] ids);
	//Encapsulate conditions with arrays in wrapper classes
	public List<User> selectUserVoByArray(UserVo userVo);
	//Encapsulate condition with list in wrapper class
	public List<User> selectUserVoByList(UserVo userVo);	
}

3. Test Code

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 {
	
	//Encapsulate the condition with a list in the wrapper class, passing the parameter is a wrapper class
	@Test
	public void test_selectUserVoByList() {
		try {
			 //Read Configuration File
			InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
			//Create a SqlSessionFactoryBuilder object to get the SqlSessionFactory object
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			//build a SqlSessionFactory object using the SqlSessionFactoryBuilder object
			SqlSessionFactory build = builder.build(in);
			//Getting session object using sqlSessionFactory
			SqlSession session = build.openSession();
			//Get the corresponding mapper interface through the session object
			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();
		}
	}
	
	//Wrap the condition with array in the wrapper class, passing the parameter is a wrapper class
	@Test
	public void test_selectUserVoByArray() {
		try {
			 //Read Configuration File
			InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
			//Create a SqlSessionFactoryBuilder object to get the SqlSessionFactory object
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			//build a SqlSessionFactory object using the SqlSessionFactoryBuilder object
			SqlSessionFactory build = builder.build(in);
			//Getting session object using sqlSessionFactory
			SqlSession session = build.openSession();
			//Get the corresponding mapper interface through the session object
			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();
		}
	}
	
	//Encapsulate the condition with an array, passing the parameter is an array
	@Test
	public void test_selectByArray() {
		try {
			 //Read Configuration File
			InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
			//Create a SqlSessionFactoryBuilder object to get the SqlSessionFactory object
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			//build a SqlSessionFactory object using the SqlSessionFactoryBuilder object
			SqlSessionFactory build = builder.build(in);
			//Getting session object using sqlSessionFactory
			SqlSession session = build.openSession();
			//Get the corresponding mapper interface through the session object
			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();
		}
	}
	
	//Encapsulating a condition with a list, the passed parameter is a list collection
	@Test
	public void test_selectByList() {
		try {
			 //Read Configuration File
			InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
			//Create a SqlSessionFactoryBuilder object to get the SqlSessionFactory object
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			//build a SqlSessionFactory object using the SqlSessionFactoryBuilder object
			SqlSessionFactory build = builder.build(in);
			//Getting session object using sqlSessionFactory
			SqlSession session = build.openSession();
			//Get the corresponding mapper interface through the session object
			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();
		}
	}

}

4. Summary

1. If you pass an array directly when you pass it, then use foreach to traverse with collection="array". This is a fixed notation, that is, the array here is not related to your actual parameter name.

2. If you pass a list collection directly when you pass it, then use foreach to traverse with collection="list", which is a fixed notation, i.e. the list here is not related to your actual reference name

3. If you pass in a class that contains array member variables directly, then collection= "your variable name" is no longer a fixed notation when using foreach traversal, i.e. the name here depends on the variable name of the member variable, for example: the member variable name is test, then collection= "test"

4. If you pass in a class that contains a list set member variable, as in case of 3

Posted by Hillu on Fri, 30 Aug 2019 21:52:49 -0700