MyBatis二级缓存使用以及MyBatis-Plus整合(SpringBoot版)

MyBatis-Plus整合

  1. 添加springboot的MP依赖
        <!-- springboot的mybatis-plus所需的依赖 -->
        <!-- <mybatis-plus.version>3.0.5</mybatis-plus.version> -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>
  1. SpringBoot配置文件中MP配置,经过测试,只需配置mybatis-plus即可,如果原来项目存在mybatis,也只需要配置mybatis-plus
mybatis-plus:
  configuration:
    cache-enabled: true
    map-underscore-to-camel-case: true
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.zsy.domain
  1. MP使用
    首先在数据库建完表后,新建对应的JavaBean类
    样例
//这些注解的具体参数这里就不一一列举,用到的话可以直接去源码查看,有中文注释
//表名
@TableName("carousel")
public class Carousel implements Serializable {

	//主键,自动增长
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    @TableField("content")
    private String content;
    @TableField("url")
    private String url;

    public Carousel() {}

    public Carousel(String content,String url) {
        this.content = content;
        this.url = url;
    }

}

接下来新建一个mapper类以及对应的mapper.xml

CarouselMapper.class

@Repository
//继承BaseMapper接口即可,里面包含了数据库操作的常用操作,具体也可以看源码
public interface CarouselMapper extends BaseMapper<Carousel> {}

CarouselMapper.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.zsy.mapper.CarouselMapper">
    
</mapper>

最后只要在service层使用mapper接口即可。


MyBatis二级缓存使用

  • 注意点:
  1. mybatis-plus 版本必须要低于2.0.9才可以使用二级缓存,否则由MP生成接口就算配置了二级缓存也没有用。
  2. 但是最新的3.x版本,实现二级缓存的配置也有了一些改变。
  3. 建议在service使用缓存,不过如果要缓存的数据不需要service层处理的话,也可以直接在mapper层缓存,这里MP的二级缓存就是直接在Mapper层进行缓存的,个人觉得主要的优点就是方便省事吧。。。
  • 下面介绍3.x的配置方法
  1. Mybatis的二级缓存实现也十分简单,只要在springboot的配置文件打开二级缓存,即
mybatis-plus:
  configuration:
    cache-enabled: true
  1. 缓存接口实现样例
public class MybatisRedisCache implements Cache {


    // 读写锁
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);

	//这里使用了redis缓存,使用springboot自动注入
	@Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private String id;

    public MybatisRedisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        this.id = id;
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public void putObject(Object key, Object value) {
        if (redisTemplate == null) {
        //由于启动期间注入失败,只能运行期间注入,这段代码可以删除
            redisTemplate = (RedisTemplate<String, Object>) ApplicationContextRegister.getApplicationContext().getBean("RedisTemplate");
        }
        if (value != null) {
            redisTemplate.opsForValue().set(key.toString(), value);
        }
    }

    @Override
    public Object getObject(Object key) {
        try {
            if (key != null) {
                return redisTemplate.opsForValue().get(key.toString());
            }
        } catch (Exception e) {
            log.error("缓存出错 ");
        }
        return null;
    }

    @Override
    public Object removeObject(Object key) {
        if (key != null) {
            redisTemplate.delete(key.toString());
        }
        return null;
    }

    @Override
    public void clear() {
        log.debug("清空缓存");
        if (redisTemplate == null) {
            redisTemplate = (RedisTemplate<String, Object>) ApplicationContextRegister.getApplicationContext().getBean("functionDomainRedisTemplate");
        }
        Set<String> keys = redisTemplate.keys("*:" + this.id + "*");
        if (!CollectionUtils.isEmpty(keys)) {
            redisTemplate.delete(keys);
        }
    }

    @Override
    public int getSize() {
        Long size = redisTemplate.execute((RedisCallback<Long>) RedisServerCommands::dbSize);
        return size.intValue();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }
}
  1. mapper.xml文件声明缓存,这里3.x只需要这样配置
<?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.zsy.mapper.CarouselMapper">
    <cache-ref namespace="com.zsy.mapper.CarouselMapper"/>
</mapper>

  1. Mapper接口使用注解
@Repository
@CacheNamespace(implementation=MybatisRedisCache.class,eviction=MybatisRedisCache.class)
public interface CarouselMapper extends BaseMapper<Carousel> {}

  • 6
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 18
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值