Mybatis如何通過注解開啟使用二級緩存
這篇文章主要介紹了Mybatis基于注解開啟使用二級緩存,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
本文主要是補(bǔ)充一下Mybatis中基于注解的二級緩存的開啟使用方法。
1.在Mybatis的配置文件中開啟二級緩存
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--開啟全局的懶加載-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--<!–關(guān)閉立即加載,其實(shí)不用配置,默認(rèn)為false–>-->
<!--<setting name="aggressiveLazyLoading" value="false"/>-->
<!--開啟Mybatis的sql執(zhí)行相關(guān)信息打印-->
<setting name="logImpl" value="STDOUT_LOGGING" />
<!--默認(rèn)是開啟的,為了加強(qiáng)記憶,還是手動加上這個配置-->
<setting name="cacheEnabled" value="true"/>
</settings>
<typeAliases>
<typeAlias type="com.example.domain.User" alias="user"/>
<package name="com.example.domain"/>
</typeAliases>
<environments default="test">
<environment id="test">
<!--配置事務(wù)-->
<transactionManager type="jdbc"></transactionManager>
<!--配置連接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test1"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.example.dao"/>
</mappers>
</configuration>
開啟緩存 <setting name="cacheEnabled" value="true"/>,為了查看Mybatis中查詢的日志,添加 <setting name="logImpl" value="STDOUT_LOGGING" />開啟日志的配置。
2.領(lǐng)域類以及Dao
public class User implements Serializable{
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
private List<Account> accounts;
省略get和set方法......
}
import com.example.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
@CacheNamespace(blocking = true)
public interface UserDao {
/**
* 查找所有用戶
* @return
*/
@Select("select * from User")
@Results(id = "userMap",value = {@Result(id = true,column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "birthday",property = "userBirthday"),
@Result(column = "sex",property = "userSex"),
@Result(column = "address",property = "userAddress"),
@Result(column = "id",property = "accounts",many = @Many(select = "com.example.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY))
})
List<User> findAll();
/**
* 保存用戶
* @param user
*/
@Insert("insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})")
void saveUser(User user);
/**
* 更新用戶
* @param user
*/
@Update("update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}")
void updateUser(User user);
/**
* 刪除用戶
* @param id
*/
@Delete("delete from user where id=#{id}")
void deleteUser(Integer id);
/**
* 查詢用戶根據(jù)ID
* @param id
* @return
*/
@Select("select * from user where id=#{id}")
@ResultMap(value = {"userMap"})
User findById(Integer id);
/**
* 根據(jù)用戶名稱查詢用戶
* @param name
* @return
*/
// @Select("select * from user where username like #{name}")
@Select("select * from user where username like '%${value}%'")
List<User> findByUserName(String name);
/**
* 查詢用戶數(shù)量
* @return
*/
@Select("select count(*) from user")
int findTotalUser();
}
3.在對應(yīng)的Dao類上面增加注釋以開啟二級緩存
@CacheNamespace(blocking = true)
4.測試
public class UserCacheTest {
private InputStream in;
private SqlSessionFactory sqlSessionFactory;
@Before
public void init()throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
}
@After
public void destory()throws Exception{
in.close();
}
@Test
public void testFindById(){
//第一查詢
SqlSession sqlSession1 = sqlSessionFactory.openSession();
UserDao userDao1 = sqlSession1.getMapper(UserDao.class);
User user1 = userDao1.findById(41);
System.out.println(user1);
//關(guān)閉一級緩存
sqlSession1.close();
//第二次查詢
SqlSession sqlSession2 = sqlSessionFactory.openSession();
UserDao userDao2 = sqlSession2.getMapper(UserDao.class);
User user2 = userDao2.findById(41);
System.out.println(user2);
sqlSession1.close();
System.out.println(user1 == user2);
}
}
(1)未開啟二級緩存時

(2)開啟二級緩存時

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Idea啟動SpringBoot程序報(bào)錯:Veb server failed to&nbs
這篇文章主要介紹了Idea啟動SpringBoot程序報(bào)錯:Veb server failed to start. Port 8082 was already in use;端口沖突的原理與解決方案,文中通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2024-10-10
基于Spring AOP @AspectJ進(jìn)階說明
這篇文章主要介紹了基于Spring AOP @AspectJ進(jìn)階說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01
Java使用正則提取字符串中的內(nèi)容的詳細(xì)步驟
這篇文章主要介紹了Java中使用正則表達(dá)式提取字符串內(nèi)容的方法,通過Pattern和Matcher類實(shí)現(xiàn),涵蓋編譯正則、查找匹配、分組捕獲、數(shù)字與郵箱提取場景,以及命名分組、非貪婪匹配等技巧,需要的朋友可以參考下2025-08-08
java依賴jave-all-deps實(shí)現(xiàn)視頻格式轉(zhuǎn)換
jave-all-deps是一款基于FFmpeg庫的Java音視頻編解碼庫,本文主要介紹了java依賴jave-all-deps實(shí)現(xiàn)視頻格式轉(zhuǎn)換,具有一定的參考價值,感興趣的可以了解一下2024-07-07
java實(shí)戰(zhàn)CPU占用過高問題的排查及解決
這篇文章給大家分享了java實(shí)戰(zhàn)CPU占用過高問題的排查及解決方法,有需要的朋友們可以學(xué)習(xí)下。2018-08-08

