使用@CachePut?更新數(shù)據(jù)庫和更新緩存
關(guān)于更新緩存 ,要注意兩點
1、@Cacheable的key
要和@CachePut 的key一致
比如:
@Cacheable(key = "'userCache'") //緩存, public Uuser findByEmail(String email) { System.err.println("執(zhí)行這里,說明緩存中讀取不到數(shù)據(jù),直接讀取數(shù)據(jù)庫...."); return redisMapper.findByEmail(email); } @CachePut(key = "'userCache'") //userCache要加‘'單引號,表示這是一個字符串 public Uuser updateSelf(String nickname, String email) { System.err.println("執(zhí)行這里,更新數(shù)據(jù)庫,更新緩存...."); uuserMapper.updateSelf(nickname, email); Uuser uuser = redisMapper.findByEmail(email); return uuser; }
2、@CachePut的返回值
要和@Cacheable的返回值一樣
如果@Cacheable 返回的是一個對象,@CachePut 返回也要是對象,否則會報類型轉(zhuǎn)換異常,如上代碼 返回的都是 Uuser.
緩存的CachePut沖突Cacheable
CachePut 跟 Cacheable放在一起, Cacheable的效果就跟 CachePut 一樣的,每次都會去查數(shù)據(jù)庫,雖然有緩存。
/** * * @param id * @return */ @Caching( put = { @CachePut(key = "T(cn.a.b.constant.RedisKey).OPEN_MEDIUM_INFO + #result.mediumBankCard", unless="#result.mediumBankCard==null or #result.status !='2'"), @CachePut(key = "T(a.b.c.constant.RedisKey).ACCOUNT_CODE + #result.accountCode", unless="!{'0','1','2','3'}.contains(#result.mediumStatus)"), @CachePut(key = "T(a.b.c.constant.RedisKey).CERT_NO+ #result.certNo", unless="#result.certNo==null or !{'0','1','2','3'}.contains(#result.status)") } , cacheable = {@Cacheable(key="T(a.b.c.constant.RedisKey).ID + #id")} ) public XXXInfo selectByPrimaryKey(Long id){ return mapper.selectByPrimaryKey(id); }
可以分解成兩個
Service.java /** * * @param id * @return */ @Caching( put = { @CachePut(key = "T(cn.a.b.constant.RedisKey).OPEN_MEDIUM_INFO + #result.mediumBankCard", unless="#result.mediumBankCard==null or #result.status !='2'"), @CachePut(key = "T(a.b.c.constant.RedisKey).ACCOUNT_CODE + #result.accountCode", unless="!{'0','1','2','3'}.contains(#result.mediumStatus)"), @CachePut(key = "T(a.b.c.constant.RedisKey).CERT_NO+ #result.certNo", unless="#result.certNo==null or !{'0','1','2','3'}.contains(#result.status)") } ) public XXXInfo selectByPrimaryKey(Long id){ return mapper.selectByPrimaryKey(id); } Mapper.java { @Cacheable(key="T(a.b.c.constant.RedisKey).ID + #p0") XXXXInfo selectByPrimaryKey(Long id); }
mybatis 接口類參數(shù)。用#參數(shù)名無效。 只能用#p0, #p1
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Springboot使用異步請求提高系統(tǒng)的吞吐量詳解
這篇文章主要介紹了Springboot使用異步請求提高系統(tǒng)的吞吐量詳解,和同步請求相對,異步不需要等待響應(yīng),隨時可以發(fā)送下一次請求,如果是同步請求,需要將信息填寫完整,再發(fā)送請求,服務(wù)器響應(yīng)填寫是否正確,再做修改,需要的朋友可以參考下2023-08-08簡單介紹區(qū)分applet和application的方法
applet和application都是Java語言編寫出來的應(yīng)用程序,本文簡單介紹了二者的不同之處,需要的朋友可以參考下2017-09-09Mybatis 數(shù)據(jù)庫連接池的實現(xiàn)示例
在Java應(yīng)用程序中,與數(shù)據(jù)庫的連接是非常昂貴的,因此,當我們使用MyBatis進行數(shù)據(jù)操作時,需要一個連接池來分配并管理這些連接,本文主要介紹了Mybatis 數(shù)據(jù)庫連接池的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下2023-10-10Eclipse+Java+Swing+Mysql實現(xiàn)電影購票系統(tǒng)(詳細代碼)
這篇文章主要介紹了Eclipse+Java+Swing+Mysql實現(xiàn)電影購票系統(tǒng)并附詳細的代碼詳解,需要的小伙伴可以參考一下2022-01-01