mybatis配置文件resultMap標簽的使用


本文為博主原創,未經允許不得轉載:

       resultMap標簽是為了映射select查詢出來結果的集合,其主要作用是將實體類中的字段與

數據庫表中的字段進行關聯映射。

     注意:當實體類中的字段與數據庫表中的字段相同時,可以將resultMap標簽中的關聯關系

忽略不寫。當實體類中的字段與數據庫表中的字段不相同時,就需要在resultMap標簽中將實體類

字段與數據庫字段一 一進行關聯映射。

       舉例如下:

1.實體類代碼:

public class Test
{
    private int id;
    private String parentId;
    private String name;
    private String enName;
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getParentId()
    {
        return parentId;
    }
    public void setParentId(String parentId)
    {
        this.parentId = parentId;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getEnName()
    {
        return enName;
    }
    public void setEnName(String enName)
    {
        this.enName = enName;
    }
   
}

2.實體類字段與數據庫表字段一致:

create table test1(
    id int(5) primary key,
    parentId int(5),
    name varchar(10),
    enName varchar(10)
)

3.關聯查詢映射resultMap使用:

 此處有兩種寫法:

第一種:將字段在resultMap標簽中都進行映射。 

<resultMap type="com.test" id="testResultMap">
    <!-- property對應實體類的屬性名稱,column為數據庫結果集的列的名稱 -->
   <id property="id" column="id" />
   <result property="parentId" column="parentId"/>
   <result property="name" column="name"/>
   <result property="enName" column="enName"/>
</resultMap>

<select id="selectList"  resultMap="testResultMap">
        select * from test1
 </select>

第二種:由於字段與數據庫字段相同,mybatis會自動進行匹配,可以寫為一下方式:

<resultMap type="com.test" id="testResultMap">
</resultMap>

<select id="selectList"  resultMap="testResultMap">
        select * from test1
</select>

 

4.實體類字段與數據庫字段不一致:

create table test2(
    id int(5) primary key,
    parent_id int(5),
    name varchar(10),
    en_name varchar(10)
)

5.關聯查詢映射使用resultMap,由於實體類字段與數據庫字段不一致,所以要將實體類字段與數據庫字段在標簽中

進行一一映射。

<!-- type指向你的javabean類,id可以自定義 -->
<resultMap type="Category" id="category">
    <!-- property對應實體類的屬性名稱,column為數據庫結果集的列的名稱 -->
   <id property="id" column="id" />
   <result property="parentId" column="parent_id" jdbcType="INTEGER"/>
   <result property="name" column="name" jdbcType="VARCHAR"/>
   <result property="enName" column="en_name" jdbcType="VARCHAR"/>
</resultMap>
<select id="selectList"  resultMap="testResultMap">
        select * from test2
    </select>

特別提示:

  <!-- 是否開啟自動駝峰命名規則(camel case)映射, -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
mybatis配置文件設置了這項后,查詢出來的字段如果帶下划線,那么就會去掉下划線,
然后采用java駝峰規則。比如數據庫字段Parent_id,那么查詢出來后,會轉為parentid,
然后去實體類Category匹配對應的字段。 因為你實體類里有下划線,所以匹配不上。
要么采用resultMap 要么禁用掉駝峰規則(不建議禁用)。如果不想該實體類的話,
建議采用resultMap


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM