首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

MyBatis resultMap 解決實體屬性與數據庫字段不一致映射問題

     編輯:Java 綜合教學

MyBatis resultMap 解決實體屬性與數據庫字段不一致映射問題

問題場景

數據庫字段 stuname 對應實體屬性 name,直接用 resultType 查詢會導致 name 為 null。

resultMap 映射配置

<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.java

public class Student {
    private Integer stuno;
    private String name;        // 對應 stuname
    private Integer stuage;
    private Date studate;
    // getter/setter/toString
}

MyBatis 配置文件

<typeAliases>
  <typeAlias type="cn.zhang.entity.Student" alias="Student"/>
</typeAliases>

DAO 接口 & 實現

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;
    }
}

運行結果對比

resultType 結果:name 為 null resultMap 結果:name 正確映射

進階用法

  • <id> 標識主鍵(影響對比/緩存)
  • <association> 一對一關聯映射
  • <collection> 一對多集合映射
  • autoMapping=true 開啟自動映射(駝峰轉下劃線)

掌握 resultMap 是 MyBatis 靈活映射的核心技能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved