Mybatis如何实现延迟加载及缓存

网友投稿 644 2023-03-27

Mybatis如何实现延迟加载及缓存

Mybatis如何实现延迟加载及缓存

一、延迟加载

1、在mybatis.xml配置文件中,开启延迟加载

2、配置mapper文件

1、一对一

* 一方

         

select="com.wuxi.daos.GradeMapper.selectById">

select="com.wuxi.daos.GradeMapper.selectById">

select * from student where id = #{id}

* 另一方

select * from grade where id = #{id}

* 测试

Student student = smapper.selectStudentGradeById(4);

System.out.println(student);

// student.hashCode();

System.out.println(student.getGrade());

2、一对多

* 一方

         

select="com.wuxi.daos.StudentMapper.selectStudentsByGrade">

select="com.wuxi.daos.StudentMapper.selectStudentsByGrade">

select * from grade where id = #{id}

* 多方

select * from student where grade_id=#{grade_id}

* 测试

Grade grade = gmapper.selectById(1);

System.out.println(grade);

// student.hashCode();

System.out.println(grade.getStudents());

二、缓存

1、一级缓存

1、概念

一级缓存是SqlSession范围的缓存,当调用SqlSession的修改,添加,删除,commit(),close()等方法时,就会清空一级缓存。

2、测试

// Student student1 = smapper.selectStudentGradeById(1);

// Student student2 = smapper.selectStudentGradeById(1);

// System.out.println(student1 == student2); // true

// ********************************

Student student1 = smapper.selectStudentGradeById(1);

Student student = nesoMUwqew Student();

student.setName("杜兰特");

student.setAge(28);

student.setSex(1);

smapper.insertStudent(student);

Student student2 = smapper.selectStudentGradeById(1);

System.out.println(student1 == student2); // false

2、二级缓存

1、开启二级缓存

1、对象需要实现Serializable接口

2、在mybatis.xml配置文件中,开启二级缓存

3、配置mapper文件

select * from student where id = #{id}

2、测试

SqlSession sqlSession1 = sqlSessionFactory.openSession();

StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);

Student student1 = mapper1.selectStudentGradeById(1);

sqlSession1.close();

SqlSession sqlSession2 = sqlSessionFactory.openSession();

StudentMapper mapper2 = sqlSession2.getMapper(StudentMapper.class);

Student student2 = mapper2.selectStudentGradeById(1);

sqlSession2.close();

// 只查询了一次数据库。二级缓存存储的是数据,并不是对象

System.out.println(student1 == student2); // false

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:详解JUC 常用4大并发工具类
下一篇:zuulGateway 通过filter统一修改返回值的操作
相关文章

 发表评论

暂时没有评论,来抢沙发吧~