mybatis 中resultType与resultMap区别

时间:2022-02-09 19:35:22

mybatis中要返回如下对象的List集合:

public class Host {

private String hostType;

private String hostAddr;

public String getHostType() {
return hostType;
}

public void setHostType(String hostType) {
this.hostType = hostType;
}

public String getHostAddr() {
return hostAddr;
}

public void setHostAddr(String hostAddr) {
this.hostAddr = hostAddr;
}

}

如果对应的表结构是:

CREATE TABLE `host` (
`host_type` varchar(32) NOT NULL COMMENT '主机类型',
`host_addr` varchar(128) NOT NULL COMMENT '主机地址',
)

用resultMap返回xml中应当这样写:

<resultMap type="net.flyingfat.common.biz.domain.Host" id="hostResult">    
<result column="host_type" property="hostType"/>
<result column="host_addr" property="hostAddr"/>
</resultMap>

<select id="getHost" resultMap="hostResult">
SELECT * FROM host
</select>
用resultType返回,xml中仅仅改为

<select id="getHost"  resultType="net.flyingfat.common.biz.domain.Host">  
SELECT * FROM host
</select>

是不够的,表结构也要改为

CREATE TABLE `host` (
`hostType` varchar(32) NOT NULL COMMENT '主机类型',
`hostAddr` varchar(128) NOT NULL COMMENT '主机地址'
)


结论:如果数据表中的字段包含下划线这种写法,最好还是用resultMap去返回;resultType返回必须保证数据库字段跟java对象的字段大小写一致。