ibatis例子(三) iterate 1

前提:目录结构参照ibatis例子(二) 下面4个文件不变

SqlMapConfig.xml

log4j.properties

t_user.sql

User.java


1.User.xml 中加入如下信息

<select id="searchProductList1" resultClass="user" parameterClass="java.util.ArrayList">
			select * from t_user 
			<dynamic prepend="WHERE">
				<iterate open="(" close=")" conjunction="OR">
					name=#keywordList[].name# AND
					sex=#keywordList[].sex#
				</iterate>
			 </dynamic>
		</select>


2.UserTest.java

package com.jinzy;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class UserTest {

	/**
	 * @param args
	 * @throws SQLException
	 * @throws IOException
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		Reader reader = Resources
				.getResourceAsReader("com/jinzy/maps/sqlMapConfig.xml");
		SqlMapClient sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
		reader.close();
		
		List keywordList = new ArrayList();
		Map param = new HashMap();
		param.put("name", "jinzy2");
		param.put("sex", "2");
		keywordList.add(param);
		Map param1 = new HashMap();
		param1.put("name", "jinzy4");
		param1.put("sex", "4");
		keywordList.add(param1);

		List users = sqlMapper.queryForList("searchProductList1", keywordList);
		
		User user1 = null;
		for (int i = 0; i < users.size(); i++) {
			user1 = (User)users.get(i);
			System.out.print(user1.getId());
			System.out.print("-");
			System.out.println(user1.getName());
		}
	}

}

3.最终输出结果

DEBUG - {conn-100000} Preparing Statement:     select * from t_user WHERE ( name=? AND sex=? OR name=? AND sex=? )        
DEBUG - {pstm-100001} Executing Statement:     select * from t_user WHERE ( name=? AND sex=? OR name=? AND sex=? ) 

4.数据库表信息



你可能感兴趣的:(ibatis例子(三) iterate 1)