[MyBatis]ResultMap结果集映射
当数据库的列名和实体类的属性名不一致会导致查询失败,因此配置Result结果集映射。
如实体类为
package com.zlc.pojo; import org.apache.ibatis.type.Alias; //实体类 @Alias("user") public class User { private int id; private String username; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public User(int id, String username, String password) { this.id = id; this.username = username; this.password = password; } public User() { } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
id username password
而数据库为
id name pwd
则配置映射
<?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"> <!--namespace=绑定一个对应的Dao/Mapper接口--> <mapper namespace="com.zlc.dao.UserMapper"> <resultMap id="UserMap" type="User"> <!--colum数据库中的字段,property中实体类的属性--> <result column="id" property="id"/> <result column="name" property="username"/> <result column="pwd" property="password"/> </resultMap> <select id="getUserById" parameterType="int" resultType="UserMap"> select * from mybatis.user where id =#{id} </select> </mapper>