mybatis中resultType和resultMap的區別及聯繫

在mybatis的mapper.xml中,我們需要定義查詢結果返回類型,常見的屬性有resultType和resultMap,那麼這兩者有什麼區別和聯繫呢。

 實體類student類代碼如下:

package com.example.demo.entity;

public class student {

    private String studentId;
    private String stringName;

    public void setStudentId(String studentId) {
        this.studentId = studentId;
    }

    public void setStringName(String stringName) {
        this.stringName = stringName;
    }

    public String getStudentId() {
        return studentId;
    }

    public String getStringName() {
        return stringName;
    }
}

1:若是實體類的字段和數據庫的字段一一對應,則可直接用resultType,resultType的值爲返回的對象,寫成如下這樣:

mapper namespace="com.example.demo.DAO.HelloWorldDAO">
    <select id="query"  resultType="student">
        select * from student
    </select>
</mapper>

  啓動項目,訪問地址,返回結果如下:

2:如果數據庫字段和實體類字段不是一一對應的,則需要採用resultMap屬性,兩者字段之間進行映射,寫法如下:

<?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">
<mapper namespace="com.example.demo.DAO.HelloWorldDAO">
    <select id="query"  resultMap="studentResult">
        select * from student
    </select>

    <resultMap type="student" id="studentResult">
        <result property="studentId" column="student_id"/>
        <result property="studentName" column="student_name"/>
    </resultMap>
</mapper>

啓動項目,訪問地址,返回結果如下:

總結:resultType和resultMap都是返回對象的,resultType實體類字段必須和數據庫字段一一對應,而resultMap如果兩者字段名不同,則可通過定義resultMap進行字段的映射。所以,一般開發中用的resultMap比較多,因爲可以自定義,所以用起來比較方便。

知識就是要不斷的學習,不斷的複習,纔會記憶的更加的深刻。加油,美好的風景一直在路上!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章