[刘阳Java]_MyBatis_映射文件的resultMap标签入门_第4讲
<resultMap>:用于解决实体类中属性和表字段名不相同的问题
- id:表示当前<resultMap>标签的唯一标识
- result:定义表字段和实体类属性的对应关系
- property:记录实体类的属性
- column:记录表的字段名称
1.一般我们在配置实体类的时候习惯将实体类中属性名字和字段名称一样,不管在后期维护还是开发过程中可读性比较好。
<?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.gxa.mapper.TeamMapper"> <resultMap type="com.gxa.pojo.Team" id="MyUser"> <id column="user_id" property="userId"/> <result column="user_name" property="user_name"/> <result column="user_pass" property="user_pass"/> <result column="user_type" property="user_type"/> <result column="user_real_name" property="user_real_name"/> </resultMap> <select id="getUser" resultMap="MyUser"> select * from team </select> </mapper>
2.但是如果当属性名称和表中列名不一样,则<resultMap>标签就解决在映射中实体和表的关联问题
1 package com.gxa.pojo; 2 3 public class MyUser { 4 private int userId; 5 private String userName; 6 private String userPass; 7 private String userType; 8 private String userRealName; 9 public int getUserId() { 10 return userId; 11 } 12 public void setUserId(int userId) { 13 this.userId = userId; 14 } 15 public String getUserName() { 16 return userName; 17 } 18 public void setUserName(String userName) { 19 this.userName = userName; 20 } 21 public String getUserPass() { 22 return userPass; 23 } 24 public void setUserPass(String userPass) { 25 this.userPass = userPass; 26 } 27 public String getUserType() { 28 return userType; 29 } 30 public void setUserType(String userType) { 31 this.userType = userType; 32 } 33 public String getUserRealName() { 34 return userRealName; 35 } 36 public void setUserRealName(String userRealName) { 37 this.userRealName = userRealName; 38 } 39 @Override 40 public String toString() { 41 return "userId = "+userId+" userName = "+userName+" userPass = "+userPass+" userType="+userType+" userRealName = "+userRealName+""; 42 } 43 }
表的字段名称如下,这样子出现和上面代码中实体类MyUser.java的属性名称和字段名称不一样
create table MyUser( user_id int primary key, user_name varchar(20), user_pass varchar(10), user_type varchar(1), user_real_name varchar(20) )
则我们在MyBatis中就需要利用<resultMap>来指定Java类中属性名称和字段名称的对应方式
<?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.gxa.mapper.TeamMapper"> <resultMap type="com.gxa.pojo.Team" id="MyUser"> <id column="user_id" property="userId"/> <result column="user_name" property="userName"/> <result column="user_pass" property="userPass"/> <result column="user_type" property="userType"/> <result column="user_real_name" property="userRealName"/> </resultMap> <select id="getUser" resultMap="MyUser"> select * from team </select> </mapper>