1. 程式人生 > >Mybatis HashMap返回型別和EL表示式顯示

Mybatis HashMap返回型別和EL表示式顯示

由於 Mybatis 語言自定義的方式,有時候,返回型別會多種多樣;我們可以通過設定ResultMap的方式,就像這樣:

<resultMap id="BaseResultMap" type="com.peng.....entity.SeckillOrder">
        <id column="orderId" property="orderId" jdbcType="CHAR"/>
        <result column="createTime" property="createTime" jdbcType="TIMESTAMP"/>
        <result
column="state" property="state" jdbcType="INTEGER"/>
<!--多對一--> <association property="seckillId" javaType="com.......entity.Seckill"> <id column="seckill_id" property="seckillId" jdbcType="BIGINT" /> <result column="sname" property="sname"
jdbcType="VARCHAR" />
... </association> <!--一對多--> <collection property="userId" ofType="com.....entity.User"> <id column="uid" property="uid" jdbcType="CHAR"/> <result column="loginname" property="loginname" jdbcType
="VARCHAR"/>
... </collection> </resultMap>

這樣非常不方便,而且,我並不希望,為了增加輸出的列名,去修改自己的實體類屬性;於是就有了HashMap返回型別。

Mybatis Mapper檔案的寫法

連線查詢時,僅僅增加一列的返回值 c.cname

 <select id="selectAll" resultMap="BaseResultMapSeckill類的返回值" >
    select *
    from t_seckill
  </select>

>>>

  <select id="selectAllToHashMap" resultType="java.util.HashMap" >
    select t.*,c.cname
    from t_seckill t INNER JOIN t_category c
    WHERE  t.cid = c.cid order by create_time desc
  </select>

查詢的結果為list對應的輸出型別 List<Map<String,Object>>
查詢的結果為為單個數據對應的輸出型別 Map<String,Object>

測試資料庫

CREATE TABLE `t_seckill` (
  `seckill_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `sname` varchar(120) DEFAULT NULL,
  `numbers` int(11) DEFAULT NULL,
  `start_time` datetime DEFAULT NULL,
  `end_time` datetime DEFAULT NULL,
  `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `seckill_desc` varchar(120) DEFAULT NULL,
  `price` decimal(8,2) DEFAULT NULL,
  `cid` bigint(20) NOT NULL,
  `image` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`seckill_id`),
  KEY `cid` (`cid`),
  CONSTRAINT `cid` FOREIGN KEY (`cid`) REFERENCES `t_category` (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 ;
public class Seckill {

    private Long seckillId;

    private String sname;

    private Integer numbers;

    private Date startTime;

    private Date endTime;

    private Date createTime;

    private String seckillDesc;

    private BigDecimal price;

    private Long cid;//所屬分類id

    private String image;
    ...
CREATE TABLE `t_category` (
  `cid` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '分類id',
  `cname` varchar(50) DEFAULT NULL COMMENT '分類名稱',
  `cdesc` varchar(100) DEFAULT NULL COMMENT '分類描述',
  PRIMARY KEY (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=1006 DEFAULT CHARSET=utf8;
public class Category {
    private Long cid;

    private String cname;

    private String cdesc;

Spring 註解方式測試

@RunWith(SpringJUnit4ClassRunner.class) // 表示繼承了SpringJUnit4ClassRunner類
@ContextConfiguration(locations = { "classpath:spring/spring-dao.xml","classpath:spring/spring-service.xml" })//匯入Mybatis的配置檔案
.....
    @Autowired
    private SeckillDao seckillDao;
     /**
     * 測試hashmap查詢
     */
    @Test
    public void testLike3(){
        List<HashMap<String,Object>> hashMapList = seckillDao.selectAllToHashMap();
        for(HashMap hashMap :hashMapList){
            Iterator iterator = hashMap.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry entry = (Map.Entry) iterator.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                System.out.println(key + ":" + value);
            }
        }
    }

輸出的結果型別

....
start_time:2017-04-20 11:23:56.0
image:57e3b072N661cd00d.jpg
create_time:2017-04-19 11:28:21.0
seckill_id:1
sname:小米(MI)Air 13.3英寸全金屬超輕薄膝上型電腦(i5-6200U 8G 256G PCIE固態硬碟 940MX獨顯 FHD WIN10)銀 
price:4899.00
numbers:99
end_time:2017-05-18 11:24:15.0 
cname:電腦辦公
seckill_desc:4.19 10點-4.21 直降100元【i5 獨立顯示卡】全高清窄邊框 8G記憶體 256G固態硬碟 支援SSD硬碟擴容 薄至14.8mm 輕至1.28kgcid:1001
.....

注意HashMap輸出的日期格式是這樣的2017-04-19 11:28:21.0而不是這種格式Thu Apr 20 12:10:06 CST 2017,可以說更方便於El表示式回顯,不用Jstl 來進行 StringDate

El表示式顯示

Controller

 List<HashMap<String,Object>> hashMapList = ....;
 model.addAttribute("seckillAlllist", hashMapList);

xx.jsp

<c:forEach var="seckill" items="${seckillAlllist}" varStatus="sort">

有三種方式
注意 key 的名稱是資料庫對應列名,你可以在Spring測試輸出時檢視

1. ${seckill['price']}
2. ${seckill.price}
3. ${seckill.get("price")}

日期格式化(不必通過<fmt:parseDate>轉換)
<fmt:formatDate   value="${seckill.start_time}" pattern="yyyy年MM月dd日 HH:mm:ss" />

 </c:forEach>

jstl標籤

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>