第4讲_MyBatis_映射文件的resultMap标签入门
程序员文章站
2022-05-28 15:58:05
...
<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>标签就解决在映射中实体和表的关联问题
package com.gxa.pojo;
public class MyUser {
private int userId;
private String userName;
private String userPass;
private String userType;
private String userRealName;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getUserRealName() {
return userRealName;
}
public void setUserRealName(String userRealName) {
this.userRealName = userRealName;
}
@Override
public String toString() {
return "userId = "+userId+" userName = "+userName+" userPass = "+userPass+" userType="+userType+" userRealName = "+userRealName+"";
}
}
表的字段名称如下,这样子出现和上面代码中实体类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>
转载于:https://www.jianshu.com/p/876bde237185