Mybatis学习笔记(五)

1、缓存

Mybatis提供查询缓存,用于减轻数据压力,提高数据库性能。

一级缓存:SqlSession级别的缓存,在操作数据库时需要构造SqlSession对象,而对象中有一个数据结构用于存储缓存数据,不同的SqlSession之间的缓存数据区域互不影响,一级缓存不需要配置。

二级缓存:mapper级别的缓存,多个SqlSession对象操作同一个mapper的sql语句,多个SqlSession对象可以共用二级缓存,二级缓存是跨SqlSession的。

2、一级缓存实例

(1)User.java

public class User {

	private Integer id;
	private String name;
	private String password;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(Integer id, String name, String password) {
		super();
		this.id = id;
		this.name = name;
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password + "]";
	}
}

(2)UserMapper.java

public interface UserMapper {

	public User findUserById(Integer id) throws Exception;
	
	public void updateUserById(User user) throws Exception;
}

(3)UserMapper.xml

<mapper namespace="com.mybatis.mapper.UserMapper">

  <select id="findUserById" parameterType="Integer" resultType="com.mybatis.bean.User">  
    select id,name,password from user where id=#{id}
  </select>
  
  <update id="updateUserById" parameterType="com.mybatis.bean.User">
  	update user set name=#{name},password=#{password} where id=#{id}
  </update>
</mapper>

(4)UserTest.java

public class UserTest {

	private SqlSessionFactory sqlSessionFactory;
	
	@Before
	public void setUp() throws Exception {
		
		String resource = "config/mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}

	@Test
	public void testFindUserById1() throws Exception{
		
		SqlSession sqlSession = sqlSessionFactory.openSession();
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		
		//第一次发起请求,查询id为1的用户
		//先从缓存中查找是否有id为1的用户信息,如果没有,则从数据库中查找用户信息
		//得到用户信息并保存在一级缓存中
		User user1 = userMapper.findUserById(1);
		System.out.println(user1);

		//第二次发起请求,查询id为1的用户
		//先从缓存中查找是否有id为1的用户信息,如果有,则直接从缓存中查找用户信息
		User user2 = userMapper.findUserById(1);
		System.out.println(user2);
		
		sqlSession.close();
	}
	
	@Test
	public void testFindUserById2() throws Exception{
		
		SqlSession sqlSession = sqlSessionFactory.openSession();
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		
		//第一次发起请求,查询id为1的用户
		User user1 = userMapper.findUserById(1);
		System.out.println(user1);
		
		//更新user1
		user1.setPassword("123456");
		userMapper.updateUserById(user1);
		//如果sqlSession执行commit操作,则会清空sqlSession中的一级缓存,目的是避免脏读
		sqlSession.commit();
		
		//第二次发起请求,查询id为1的用户
		User user2 = userMapper.findUserById(1);
		System.out.println(user2);
		
		sqlSession.close();
	}
}

(5)db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/hwd
jdbc.username=root
jdbc.password=123456

(6)mybatis-config.xml

<configuration>
	<properties resource="config/db.properties"></properties>
    <environments default="development">
        <environment id="development">
            <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.mybatis.mapper"/>
    </mappers>
</configuration>

(7)log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

3、二级缓存实例

(1)User.java

/**
 * 实现序列化接口,目的是实现反序列化操作,因为二级缓存数据存储介质多种多样,不一定保存在内存中
 * @author vineg
 *
 */
public class User implements Serializable {

	private Integer id;
	private String name;
	private String password;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(Integer id, String name, String password) {
		super();
		this.id = id;
		this.name = name;
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password + "]";
	}
}

(2)UserMapper.java

public interface UserMapper {

	public User findUserById1(Integer id) throws Exception;
	
	public User findUserById2(Integer id) throws Exception;
	
	public void updateUserById(User user) throws Exception;
}

(3)UserMapper.xml

<mapper namespace="com.mybatis.mapper.UserMapper">

  <!-- 开启本mapper的二级缓存 -->
  <cache/>
  <select id="findUserById1" parameterType="Integer" 
  		resultType="com.mybatis.bean.User">  
    select id,name,password from user where id=#{id}
  </select>
  
  <!-- 在statement中设置useCache="false"(默认值是true),可以禁用当前select语句的二级缓存 -->
  <select id="findUserById2" parameterType="Integer" 
  		resultType="com.mybatis.bean.User" useCache="false">  
    select id,name,password from user where id=#{id}
  </select>
  
  <update id="updateUserById" parameterType="com.mybatis.bean.User">
  	update user set name=#{name},password=#{password} where id=#{id}
  </update>
</mapper>

(4)UserTest.java

public class UserTest {

	private SqlSessionFactory sqlSessionFactory;
	
	@Before
	public void setUp() throws Exception {
		
		String resource = "config/mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}
	
	@Test
	public void testFindUserById1() throws Exception{
		
		SqlSession sqlSession1 = sqlSessionFactory.openSession();
		UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
		//第一次发起请求,查询id为1的用户
		//先从缓存中查找是否有id为1的用户信息,如果没有,则从数据库中查找用户信息
		User user1 = userMapper1.findUserById1(1);
		System.out.println(user1);
		//执行关闭操作,目的是将sqlSession1中的数据写到二级缓存
		sqlSession1.close();

		SqlSession sqlSession2 = sqlSessionFactory.openSession();
		UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
		//第二次发起请求,查询id为1的用户
		//先从缓存中查找是否有id为1的用户信息,如果有,则直接从缓存中查找用户信息
		User user2 = userMapper2.findUserById1(1);
		System.out.println(user2);
		sqlSession1.close();
	}
	
	@Test
	public void testFindUserById2() throws Exception{
		
		SqlSession sqlSession1 = sqlSessionFactory.openSession();
		UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
		//第一次发起请求,查询id为1的用户
		User user1 = userMapper1.findUserById1(1);
		System.out.println(user1);
		//执行关闭操作,目的是将sqlSession1中的数据写到二级缓存
		sqlSession1.close();

		SqlSession sqlSession2 = sqlSessionFactory.openSession();
		UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
		User user2 = new User(1, "tom", "123");
		userMapper2.updateUserById(user2);
		//执行commit,清空userMapper下的二级缓存
		sqlSession2.commit();
		sqlSession2.close();
		
		SqlSession sqlSession3 = sqlSessionFactory.openSession();
		UserMapper userMapper3 = sqlSession3.getMapper(UserMapper.class);
		//第二次发起请求,查询id为1的用户
		User user3 = userMapper3.findUserById1(1);
		System.out.println(user3);
		sqlSession1.close();
	}
	
	@Test
	public void testFindUserById3() throws Exception{
		
		SqlSession sqlSession1 = sqlSessionFactory.openSession();
		UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
		//第一次发起请求,查询id为1的用户
		User user1 = userMapper1.findUserById2(1);
		System.out.println(user1);
		sqlSession1.close();

		SqlSession sqlSession2 = sqlSessionFactory.openSession();
		UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
		//第二次发起请求,查询id为1的用户
		//由于禁用了statement的id是findUserById2的二级缓存,所以用户信息还是从数据库中查找
		User user2 = userMapper2.findUserById2(1);
		System.out.println(user2);
		sqlSession1.close();
	}
}

(5)db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/hwd
jdbc.username=root
jdbc.password=123456

(6)mybatis-config.xml

<configuration>
	<properties resource="config/db.properties"></properties>
	<settings>
		<!-- 开启二级缓存 -->
		<setting name="cacheEnabled" value="true" />
	</settings>
    <environments default="development">
        <environment id="development">
            <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.mybatis.mapper"/>
    </mappers>
</configuration>

(7)log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值