有时我们厌倦了为每个查询写一个Entity类,这时Map开始发挥它的功效。

对于要返回“学号,班级,姓名”结果的查询,可以这样写Mapper:

<select id="selectStudent">

    select s.code as sNo , s.name as sName, c.name as cName

    from xStudent s, xClass c

    where s.cID = c.ID

</select>


如下声明我们的dao方法:

public List<Map<String, Object>> selectStudent(Map<String, Object> parameter) {

    return getSqlSession().selectList(getStatement("selectStudent"), parameter);

}

如果要将该查询结果转为JSON字符串返回,那么我们就可以直接将List<Map<String, Object>转为JSON,逻辑层不需要任何代码。

如果返回的结果集需要按select中的字段顺序返回,那么将resultType="java.util.HashMap" 换为resultType="java.util.LinkedHashMap"

------------------------------华丽分割线-----------------------------

使用Map封装查询结果时注意数据的类型映射

对于如下的Mapper

<select id="selectStudent">

    select s.code as sNo , concat(s.firstName, s.lastName) as sName

    from xStudent s

</select>


Mybatis会傻傻的将sName的数据类型映射为byte[], 因为我们没有提供entity,mybatis也不知道我们想要什么类型,而sName是计算出来的值,mybatis也没有办法从数据库中获取字段的值,所以它就将其封装为byte[],解决办法很简单,加一个cast 函数

<select id="selectStudent">

select s.code as sNo , cast(concat(s.firstName, s.lastName) AS CHAR) as sName

from xStudent s

</select>

------------------------------------华丽分割线--------------------------------

之前讲到了orcale的字符串与日期等类型的转换,现在我们来看看MySQL是怎么转换的。比起orcale,MySQL相比之下就简单得多了,只需要一个Cast()函数就能搞定。其语法为:Cast(字段名 as 转换的类型 ),其中类型可以为:

CHAR[(N)] 字符型 
DATE  日期型
DATETIME  日期和时间型
DECIMAL  float型
SIGNED  int
TIME  时间型

例如表table1

date

2015-11-03 15:31:26

select cast(date as signed) as date from  table1;

结果如下:

date

20151103153126


select cast(date as char) as date from  table1;

结果如下:

date

2015-11-03 15:31:26



select cast(date as datetime) as date from  table1;

结果如下:

date


2015-11-03 15:31:26


select cast(date as date) as date from  table1;

结果如下:

date


2015-11-03


select cast(date as time) as date from  table1;

结果如下:

date

15:31:26

这里date对应日期,time对应时间