1、数据库中表的设计
2、实体类
public class User {
private int id;
private String name;
private String 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;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password="
+ password+ "]";
}
}
3、mapper映射文件
<select id="selectUser" resultType="User">
select * from user where id = #{id}
</select>
4、问题:密码没有获取到
原因:mybatis会根据查询的列名(会将列名转为小写) 去进行设值(列名setter方法)
5、解决列名和属性名不一致的办法
a)为列名指定别名 别名和java实体类的属性名一致
<select id="selectUser" resultType="User">
select id,Name,pwd password from user where id = #{id}
</select>
b)设置结果映射类型
<select id="selectUser" resultMap="UserMap">
select id,name,pwd from user where id = #{id}
</select>
<resultMap type="User" id="UserMap">
<!-- id为主键 -->
<id column="id" property="id"/>
<!-- column是数据库中表的列名 property是对应实体类的属性名 -->
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>