1、结果集映射
就是将返回的记录,逐个字段映射到java对象上;如果数据库字段与java对象的成员变量名对应的话,则使用resultClas即可
2、实现
结合 ibatis初探这篇文章中提到的project 修改以下文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap> <typeAlias alias = "user" type = "com.jiexun.User" /> <resultMap class="user" id="dbUser"> <!--property值 是类的成员名,column 是数据库字段名 --> <result property="userId" column="id" jdbcType="int" /> <result property="userName" column="name" jdbcType="varchar" /> </resultMap> <select id="getUser" parameterClass = "int" resultMap="dbUser"> select * from user where user.id = #id# </select> <!-- 对象传参 user的属性中有id name 成员变量 --> <insert id="addUser" parameterClass="user"> insert into user values(#id#,#name#) </insert> <!-- Map传参 --> <insert id="addUser2" parameterClass="java.util.HashMap"> insert into user values(#id#,#name#) </insert> </sqlMap>
user类主要是修改了成员名,以便有鲜明的对比
package com.jiexun; public class User { public int userId; public String userName; public int getId() { return userId; } public void setId(int id) { this.userId = id; } public String getName() { return userName; } public void setName(String name) { this.userName = name; } }
import java.io.Reader; import java.util.HashMap; import java.util.List; import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; import com.jiexun.User; public class testIbatis { /** * @param args */ public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub int id = 1002; User newUser = new User(); newUser.setId(1001); newUser.setName("LS"); String config = "com/jiexun/xml/ibatis.xml"; Reader reader = Resources.getResourceAsReader(config); SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader); //对象传参 插入 // Object obj = sqlMap.insert("addUser",newUser); // System.out.println("插入新用户返回值:" + obj); // // //Map传参 插入 // HashMap paraMap = new HashMap<String, Object>(); // paraMap.put("id", "1002"); // paraMap.put("name", "WWN"); // Object obj2 =sqlMap.insert("addUser2",paraMap); //查询 List<User> list = (List<User>)sqlMap.queryForList("getUser",id); System.out.println("执行select完毕"); for (User user : list) { System.out.println(user.userId + ": " + user.userName); } } }