天天看点

关于mybatis增加缓存引入的坑

mapper.xml的配置文件里面开启了缓存,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pp.dao.mapper.ProductMapper">
	
	<cache eviction="LRU" flushInterval="3000" size="1024" readOnly="true" />
	
	<resultMap id="queryProductListMap" type="java.util.HashMap">
		<result column="id" property="id" />
		<result column="name" property="name" />
		<result column="price" property="price" />
		<result column="create_time" property="createTime" javaType="java.util.Date"/>
	</resultMap>
	
	<select id="queryProductList" resultMap="queryProductListMap">
		select id,name,price,create_time 
		from tb_product 
		where is_del=0 
		order by create_time desc
	</select>
	
</mapper>
           

缓存时间是3s,注意返回的结果,createTime类型是java.util.Date

java代码如下:

package com.pp.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.pp.dao.ProductMapper;

@RestController
public class HomeController {
	@Autowired
	private ProductMapper productMapper;
	
	@RequestMapping(value = "/list")
	public Object list() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Map<String, Object>> list = productMapper.queryProductList();
		Date now = new Date();
		for (Map<String, Object> map : list) {
			Date date = (Date)map.get("createTime");
			int days = (int)((now.getTime() - date.getTime())/1000/60/60/24);
			if (days > 3) {
				map.put("exitable", 1);
			} else {
				map.put("exitable", 0);
			}
			map.put("createTime", sdf.format(date));
		}
		return list;
	}
}
           

运行代码之后,如果在3s(缓存时间)之内,多次访问,就会报错。

原因就在于 Date date = (Date)map.get("createTime"); 这一行把map里面的对象转换成Date(第一次这里面的对象的确是Date),

map.put("createTime", sdf.format(date)); 这一行,又把map里面的对象转换成字符串了。

在缓存时间之内访问,每次返回的是缓存的list<Map>,第一次把数据改掉之后,第二次那个对象就不是Date类型的对象了,强转自然就报错了。

问题定位到之后,解决方法就有很多了

最主要的是,不要改productMapper.queryProductList();返回的数据,可以把productMapper.queryProductList();返回的数据clone一份,去修改clone之后的数据

需要注意的是,要深度clone

继续阅读