Requirement: Find out the record with a given id:
- <select id="getEmpsByConditionForeach" resultType="com.test.beans.Employee">
- SELECT * FROM tb1_emplyee WHERE id IN
- <foreach collection="list" item="item_id" separator="," open="(" close=")">
- #{item_id}
- </foreach>
- </select>
Regarding the foreach tag, there are several properties that should be noted:
- collection: Specifies the collection to traverse:
- The parameters of the list type will be specially processed and encapsulated in the map, and the key of the map is called list
- item: assign the currently traversed element to the specified variable
- separator: the separator between each element
- open: traverse all the results and splicing a starting character
- close: traverse all the results and splicing an ending character
- index: index. When traversing the list, the index is the index, and the item is the current value
- When traversing the map, the index represents the key of the map, and the item is the value of the map.
- #{variable name} can take out the value of the variable, which is the element currently traversed
testing method:
- @Test
- public void testDynamicSqlTest() throws IOException{
- SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
- //1. The obtained SqlSession will not automatically submit data
- SqlSession openSession = sqlSessionFactory.openSession();
- try
- {
- EmployeeMapperDymanicSQL mapper=openSession.getMapper(EmployeeMapperDymanicSQL.class);
- /*Employee employee=new Employee(1,"lili",null,"1");*/
- List<Employee> emps=mapper.getEmpsByConditionForeach(Arrays.asList(1,2,3,4));
- for (Employee e:emps){
- System.out.println(e);
- }
- }
- finally {
- openSession.close();
- }
- }
The foreach tag can also implement batch insertion (deletion) of data:
Here is an example of batch inserting data:
- <insert id="addEmps">
- INSERT INTO tb1_emplyee(last_name,email,gender,d_id)
- VALUES
- <foreach collection="emps" item="emp" separator=",">
- (#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
- </foreach>
- </insert>
Corresponding interface:
- public void addEmps(@Param("emps")List<Employee> emps);
testing method
- @Test
- public void testBatchSave() throws IOException{
- SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
- //1. The obtained SqlSession will not automatically submit data
- SqlSession openSession = sqlSessionFactory.openSession();
- try
- {
- EmployeeMapperDymanicSQL mapper=openSession.getMapper(EmployeeMapperDymanicSQL.class);
- List<Employee> emps=new ArrayList<Employee>();
- emps.add(new Employee(null,"Eminem","[email protected]","1",new Department(1)));
- emps.add(new Employee(null,"2Pac","[email protected]","1",new Department(1)));
- mapper.addEmps(emps);
- openSession.commit();
- }
- finally {
- openSession.close();
- }
- }