MyBatis的返回参数类型分两种
1. 对应的分类为:
1.1.resultMap:
1.2.resultType:
2 .对应返回值类型:
2.1.resultMap:结果集
2.2.resultType:int,string ,long ,class 可以返回HashMap
1.resultMap 类型为 java.util.HashMap
xml
<select id="findTownList" resultMap="TownMap"> SELECT townid,townname xxx WHERE zoneid = #{zoneid} </select> <resultMap type="java.util.HashMap" id="TownMap"> <result column="townid" property="townid"/> <result column="townname" property="townname"/> </resultMap>
Mapper
@Mapper public interface DivisionMapper {
public List<HashMap> findTownList(String id); }
注意为list
单元测试类
@Autowired xxMapper xxMapper; @Test public void findTownList() {
List<HashMap> townList = xxMapper.findTownList("02");System. out.println(townList) ; }
测试结果:[{townname=x镇, townid=100}, {townname=xx镇, townid=101}]
注意:这种放的优点 不需要POJO类,输出结果没有多余字段,数据库字段名与返回给前端的名字可以随意映射,自由度高。
最后xml可以精简为
<select id="findTownList" resultType="java.util.HashMap"> SELECT townid,townname FROM xxx WHERE id = #{id} </select>利用.resultType:int,string ,long ,class 可以返回HashMap
假如需要结果映射修改字段名的话
<select id="findTownList" resultType="java.util.HashMap"> SELECT townid AS "TOWNid",townname FROM xxx WHERE zoneid = #{zoneid} </select>
利用sql语句的as来解决(最终方案比较简单)
注意:利用mybatis 动态查询一条记录,而返回是一个map(resultType=”java.util.Map”,键是字段名,值是字段值),比如操作数据库是通过存储过程或者是直接传一个String sql="select * from emp where e_id=1"字符串来返回一个map。
如果某一列的值为空。查询这条记录时就不显示这列了。《===map中无此对应的键
2.resultMap 类型为 POJO类
mapper
@Mapper public interface DivisionMapper { public List<Town> findTownList(String zoneid); }
xml
<select id="findTownList2" resultMap="TownMap2"> SELECT townid,townname FROM xx WHERE zoneid = #{zoneid} </select> <resultMap type="Town" id="TownMap2"> <result column="townid" property="townid"/> <result column="townname" property="townname"/> </resultMap> </mapper>
pojo类省略 重写tostring()方法
测试类
List<Town> townList = xxMapper.findTownList2("50");结果
[Town{townid='101095001', townname='x镇'}]