1、返回 int 、 String 等 直接使用resultType即可
2、返回的是对象
2.1 可用resultmap做映射:
主要用在进行复杂联合查询上,因为进行简单查询是没有什么必要的。
2.2 使用resultType:
一直以来,在sqlmap文件中,对于数据库中的下划线字段转驼峰,我们都是通过resultmap来做的,如下:
<resultMap id="ISTableStatistics" type="com.medsoft.perfstat.pojo.ISTableStatistics" >
<result column="TABLE_SCHEMA" property="tableSchema" jdbcType="VARCHAR" />
<result column="TABLE_NAME" property="tableName" jdbcType="VARCHAR" />
<result column="ROWS_READ" property="rowsRead" jdbcType="BIGINT" />
<result column="ROWS_CHANGED" property="rowsChanged" jdbcType="BIGINT" />
<result column="ROWS_CHANGED_X_INDEXES" property="rowsChangedXIndexes" jdbcType="BIGINT" />
</resultMap>
<select id="selectISTableStatistics" parameterType="java.util.Map" resultMap="ISTableStatistics">
select
ews.TABLE_SCHEMA,
ews.TABLE_NAME,
ews.ROWS_READ,
ews.ROWS_CHANGED,
ews.ROWS_CHANGED_X_INDEXES
from information_schema.TABLE_STATISTICS ews
where ews.TABLE_SCHEMA not in (‘perf_stat‘,‘mysql‘,‘sys‘,‘performance_schema‘,‘information_schema‘)
and ews.rows_read > 0
</select>
这是件挺无聊的事情。有两种方法:
2.2.1 其实mybatis是支持自动转的,只要在mybatis-config.xml中加上mapUnderscoreToCamelCase setting即可,如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="conf/db-dialect.properties" />
<settings>
<setting name="logImpl" value="LOG4J"/>
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
</configuration>
这样配置之后,就不需要人工写上面的resultMap了,直接resultType就可以了,对于字段超多的情况,这可以省去不少没意义的时间花费。2.2.2 给查询出的字段起别名,该别名和需要映射的java的属性名一致即可。比如:
ChatUser类有三个属性:id, nickName, logo,
实现映射如下:
<select id="getMainUserByChatGroupId" parameterType="java.lang.String"
resultType="com.ChatUser">
SELECT
cu.id, cu.nick_name nickName, cu.logo
FROM
chat_group cg, chat_user cu
WHERE
cg.id = #{chatGroupId} and
cg.main_user_id = cu.id
</select>
对下划线z字段 nick_name 起别名 nickName即可。