延遲加載(按需加載、懶加載)在真正使用數據時才發起查詢,不用的時候不查詢java
MyBatis一級緩存:mysql
指的是MyBatis中SqlSession對象的緩存,當咱們執行查詢以後,查詢的結果會同時存入到SqlSession爲咱們提供一塊區域中。sql
該區域的結構是一個Map。當咱們再次查詢一樣的數據,mybatis會先去sqlsession中查詢是否有,有的話直接拿出來用。
當SqlSession對象消失時,mybatis的一級緩存也就消失了apache
當調用SqlSession的修改、添加、刪除、commit()、close()等方法時,就會清空一級緩存緩存
MyBatis二級緩存 微信
MyBatis中SqlSessionFactory對象的緩存。由同一個SqlSessionFactory對象建立的SqlSession共享其緩存
二級緩存使用步驟:session
1.讓MyBatis框架支持二級緩存(在sqlmapconfig.xml中配置)mybatis
<setting name="cacheEnabled" value="true"/>
2.讓當前的映射文件支持二級緩存(在UserDao.xml中配置)app
<cache/>
3.讓當前的操做支持二級緩存(在select標籤中配置)框架
useCache="true"
二級緩存中存放的內容是數據,而不是對象
另一種是使用註解,在Dao類上面
@CacheNamespace(blocking = true)
實體類
import java.io.Serializable; public class Account implements Serializable { private Integer id; private Integer uid; private Double money; private User user; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String toString() { return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}'; } }
import java.io.Serializable; import java.util.Date; import java.util.List; public class User implements Serializable { private Integer id; private String username; private String address; private String sex; private Date birthday; private List<Account> accounts; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public List<Account> getAccounts() { return accounts; } public void setAccounts(List<Account> accounts) { this.accounts = accounts; } @Override public String toString() { return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}'; } }
Dao層
import com.jinke.domain.Account; import org.apache.ibatis.annotations.One; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.mapping.FetchType; import java.util.List; public interface AccountDao { @Select("select * from account") @Results(id = "accountMap", value = { @Result(id = true, property = "id", column = "id"), @Result(property = "uid", column = "uid"), @Result(property = "money", column = "money"), @Result(property = "user", column = "uid", one = @One(select = "com.jinke.dao.UserDao.findById", fetchType = FetchType.LAZY)) }) List<Account> findAll(); @Select("select * from account where uid = #{uid}") List<Account> findAccountByUid(Integer uid); }
import com.jinke.domain.User; import org.apache.ibatis.annotations.*; import org.apache.ibatis.mapping.FetchType; import java.util.List; /*開啓二級緩存*/ @CacheNamespace(blocking = true) public interface UserDao { @Select("select * from user") @Results(id = "userMap", value = {@Result(id = true, property = "id", column = "id"), @Result(property = "username", column = "username"), @Result(property = "sex", column = "sex"), @Result(property = "address", column = "address"), @Result(property = "birthday", column = "birthday"), @Result(property = "accounts", column = "id", many = @Many(select = "com.jinke.dao.AccountDao.findAccountByUid", fetchType = FetchType.EAGER))} ) List<User> findAll(); @Select("select * from user where id = #{id}") @ResultMap(value = "userMap") User findById(Integer id); }
註解開發就不須要xml配置映射關係了
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 2.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbcConfig.properties"/>
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="true"/>
<!--配置開啓二級緩存-->
<setting name="cacheEnabled" value="true"/>
</settings>
<typeAliases>
<!--用於配置別名的包,該包下實體類都會註冊別名,即類名,且不區分大小寫-->
<package name="com.jinke.domain"/>
</typeAliases>
<!--配置環境-->
<environments default="mysql">
<!--配置mysql的環境-->
<environment id="mysql">
<!--配置事務-->
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--配置映射文件的位置-->
<mappers>
<package name="com.jinke.dao"/>
</mappers>
</configuration>
測試類
import com.jinke.dao.AccountDao; import com.jinke.dao.RoleDao; import com.jinke.dao.UserDao; import com.jinke.domain.Account; import com.jinke.domain.Role; import com.jinke.domain.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.InputStream; import java.util.List; public class MyBatisTest { private InputStream in; private SqlSession sqlSession; private UserDao userDao; private AccountDao accountDao; private RoleDao roleDao; private SqlSessionFactory factory; @Before public void init() throws Exception { in = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); factory = builder.build(in); sqlSession = factory.openSession(); userDao = sqlSession.getMapper(UserDao.class); accountDao = sqlSession.getMapper(AccountDao.class); roleDao = sqlSession.getMapper(RoleDao.class); } @After public void destroy() throws Exception { sqlSession.commit(); sqlSession.close(); in.close(); } @Test public void testFindAccount() { List<Account> accounts = accountDao.findAll(); for (Account account : accounts) { System.out.println(account + " " + account.getUser()); } } @Test public void testFindUser() { List<User> users = userDao.findAll(); for (User user : users) { System.out.println(user + " " + user.getAccounts()); } } @Test public void testFindRole() { List<Role> roles = roleDao.findAll(); for (Role role : roles) { System.out.println(role + " " + role.getUsers()); } } @Test public void testFirstLevelCache() { User user = userDao.findById(1); System.out.println(user); //清除一級緩存
sqlSession.clearCache(); User user2 = userDao.findById(1); System.out.println(user2); System.out.println("user==user2?" + (user == user2)); } @Test public void testClearCache() { //測試二級緩存
SqlSession session1 = factory.openSession(); UserDao userDao1 = session1.getMapper(UserDao.class); User user1 = userDao1.findById(1); System.out.println(user1); session1.close(); SqlSession session2 = factory.openSession(); UserDao userDao2 = session2.getMapper(UserDao.class); User user2 = userDao2.findById(1); System.out.println(user2); session1.close(); System.out.println("user==user2?" + (user1 == user2)); } }
總的來講,簡單的查詢能夠用註解,方便快速,可是太複雜的sql仍是用xml
歡迎關注個人微信公衆號:安卓圈