測試mybatis裡foreach用法
阿新 • • 發佈:2018-12-29
1.介紹
連結:http://www.mybatis.org/mybatis-3/zh/dynamic-sql.htmlforeach
動態 SQL 的另外一個常用的必要操作是需要對一個集合進行遍歷,通常是在構建 IN 條件語句的時候。比如:
<selectid="selectPostIn"resultType="domain.blog.Post"> SELECT * FROM POST P WHERE ID in <foreachitem="item"index="index"collection="list"open="("separator=","close=")"> #{item} </foreach></select>
foreach 元素的功能是非常強大的,它允許你指定一個集合,宣告可以用在元素體內的集合項和索引變數。它也允許你指定開閉匹配的字串以及在迭代中間放置分隔符。這個元素是很智慧的,因此它不會偶然地附加多餘的分隔符。
注意 你可以將任何可迭代物件(如列表、集合等)和任何的字典或者陣列物件傳遞給foreach作為集合引數。當使用可迭代物件或者陣列時,index是當前迭代的次數,item的值是本次迭代獲取的元素。當使用字典(或者Map.Entry物件的集合)時,index是鍵,item是值。
到此我們已經完成了涉及 XML 配置檔案和 XML 對映檔案的討論。下一部分將詳細探討 Java API,這樣才能從已建立的對映中獲取最大利益。
2.用法
List,Array,Map3.測試例子
參考:https://www.cnblogs.com/fangyu19900812/p/6046209.html
mapper:
package com.example.demo.mapper; import java.util.List; import java.util.Map; import com.example.demo.entity.UserEntity; public interface UserMapper { List<UserEntity> getAll(); void insert(UserEntity user); List<UserEntity> testForeachOne(List<Integer> ids); List<UserEntity> testForeachTwo(int[] ids); List<UserEntity> testForeachThree(Map<String,Object> map); }
測試類:
package com.example.demo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.example.demo.entity.UserEntity;
import com.example.demo.mapper.UserMapper;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestForeach {
@Autowired
UserMapper mapper;
@Test
public void testAll() {
List<UserEntity> list = mapper.getAll();
for(UserEntity user:list) {
System.out.print(user.toString());
}
}
@Test
public void testForeachOne() throws Exception{
List ids = new ArrayList();
ids.add(37);
ids.add(38);
ids.add(39);
List<UserEntity> users = mapper.testForeachOne(ids);
for(UserEntity user:users) {
System.out.println(user);
}
}
@Test
public void testForeachTwo() throws Exception{
int[] ids = new int[] {37,38,39};
List<UserEntity> users = mapper.testForeachTwo(ids);
for(UserEntity user:users) {
System.out.println(user);
}
}
@Test
public void testForeachThree() throws Exception{
List ids = new ArrayList();
ids.add(37);
ids.add(38);
ids.add(39);
Map map = new HashMap();
map.put("ids", ids);
List<UserEntity> users = mapper.testForeachThree(map);
for(UserEntity user:users) {
System.out.println(user);
}
}
}
mapper.xml
<?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.example.demo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.demo.entity.UserEntity">
<id column="id" property="id" jdbcType="BIGINT" />
<result column="userName" property="userName" jdbcType="VARCHAR" />
<result column="passWord" property="password" jdbcType="VARCHAR" />
<result column="user_sex" property="userSex"
javaType="com.example.demo.enums.UserSexEnum" />
<result column="nick_name" property="nickName" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List">
id, userName, passWord, user_sex, nick_name
</sql>
<select id="getAll" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
FROM users
</select>
<!-- 測試foreach list -->
<select id="testForeachOne" parameterType="java.util.List"
resultMap="BaseResultMap">
select * from users where id in
<foreach collection="list" index="index" item="item" open="("
separator="," close=")">
#{item}
</foreach>
</select>
<!-- 測試foreach array -->
<select id="testForeachTwo" parameterType="java.util.List"
resultMap="BaseResultMap">
select * from users where id in
<foreach collection="array" index="index" item="item" open="("
separator="," close=")">
#{item}
</foreach>
</select>
<!-- 測試foreach map -->
<select id="testForeachThree" parameterType="java.util.HashMap"
resultMap="BaseResultMap">
select * from users where id in
<foreach collection="ids" index="index" item="item" open="("
separator="," close=")">
#{item}
</foreach>
</select>
</mapper>
資料庫:
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵id',
`userName` varchar(32) DEFAULT NULL COMMENT '使用者名稱',
`passWord` varchar(32) DEFAULT NULL COMMENT '密碼',
`user_sex` varchar(32) DEFAULT NULL,
`nick_name` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
注意事項:
問題一:
Caused by: org.apache.ibatis.type.TypeException: Could not resolve type alias 'BaseResultMap'. Cause: java.lang.ClassNotFoundException: Cannot find class: BaseResultMap
at org.apache.ibatis.type.TypeAliasRegistry.resolveAlias(TypeAliasRegistry.java:120) ~[mybatis-3.4.0.jar:3.4.0]
at org.apache.ibatis.builder.BaseBuilder.resolveAlias(BaseBuilder.java:149) ~[mybatis-3.4.0.jar:3.4.0]
at org.apache.ibatis.builder.BaseBuilder.resolveClass(BaseBuilder.java:116) ~[mybatis-3.4.0.jar:3.4.0]
... 73 common frames omitted
Caused by: java.lang.ClassNotFoundException: Cannot find class: BaseResultMap
at org.apache.ibatis.io.ClassLoaderWrapper.classForName(ClassLoaderWrapper.java:200) ~[mybatis-3.4.0.jar:3.4.0]
at org.apache.ibatis.io.ClassLoaderWrapper.classForName(ClassLoaderWrapper.java:89) ~[mybatis-3.4.0.jar:3.4.0]
at org.apache.ibatis.io.Resources.classForName(Resources.java:261) ~[mybatis-3.4.0.jar:3.4.0]
at org.apache.ibatis.type.TypeAliasRegistry.resolveAlias(TypeAliasRegistry.java:116) ~[mybatis-3.4.0.jar:3.4.0]
... 75 common frames omitted
遇到這種錯,注意mapper.xml檔案中將resultType改為resultMap