5.1 数据库中的字段
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-48mgZnJm-1616847137223)(https://note.youdao.com/yws/api/personal/file/48CAFAD4AC954014AE543CB37D92E9E9?method=download&shareKey=974ce6ecbf4647293dd73f0212e9ca9a)]
新建一个项目,拷贝之前的,测试实体类字段不一致情况
问题
package com.mybatis.pojo;
//实体类
public class User {
private int id;
private String name;
private String password;
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public User(){}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
User{id=1, name='刘通', password='null'}
Process finished with exit code 0
//select id,name,pwd from mybatis.user where id={id}
//类型处理器
//select id,name,pwd as password from mybatis.user where id ={id}
解决办法:
- 起别名
<!--根据id查询用户-->
<select id="getUserById" parameterType="int" resultType="com.mybatis.pojo.User">
select id,name,pwd as password from mybatis.user where id=#{id}
</select>
5.2、resultMap
结果集映射
id name pwd
id name password
解决办法2
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--cloumn数据库中的字段,property实体类中的属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="UserMap">
select * from mybatis.user where id=#{id}
</select>
- resultMap元素是MyBatis中最强大的元素
- ResulMap的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了
- ResultMap最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式的用到他们