數據庫字段 stuname 對應實體屬性 name,直接用 resultType 查詢會導致 name 為 null。
<mapper namespace="cn.zhang.dao">
<resultMap type="Student" id="findstudent">
<result property="name" column="stuname" />
</resultMap>
<select id="findAll" resultMap="findstudent">
select * from student
</select>
</mapper>
property = 實體屬性,column = 數據庫列名(或別名)。
Student.javapublic class Student {
private Integer stuno;
private String name; // 對應 stuname
private Integer stuage;
private Date studate;
// getter/setter/toString
}
<typeAliases> <typeAlias type="cn.zhang.entity.Student" alias="Student"/> </typeAliases>
public interface StudentDao { List<Student> findAll() throws IOException; }
public class StudentDaoImpl implements StudentDao {
public List<Student> findAll() throws IOException {
List<Student> list = session.selectList("findAll");
session.close(); return list;
}
}

<id> 標識主鍵(影響對比/緩存)<association> 一對一關聯映射<collection> 一對多集合映射autoMapping=true 開啟自動映射(駝峰轉下劃線)掌握 resultMap 是 MyBatis 靈活映射的核心技能。