mybatis延遲載入和快取
阿新 • • 發佈:2020-09-10
一、延遲載入
1、在mybatis.xml配置檔案中,開啟延遲載入 <settings> <!--開啟延遲載入--> <setting name="lazyLoadingEnabled" value="true"></setting> <setting name="aggressiveLazyLoading" value="false"></setting> <!--延遲載入觸發方法,equals、hashCode、toString都會觸發載入--> <setting name="lazyLoadTriggerMethods" value="hashCode"></setting> </settings> 2、配置mapper檔案 1、一對一 * 一方 <resultMap id="studentGradeById" type="Student"> <id column="id" property="id"></id> <result column="name" property="name"></result> <result column="age" property="age"></result> <result column="sex" property="sex"></result>
<!--關閉延遲載入會做兩次查詢--> <association column="grade_id" property="grade" javaType="Grade" select="com.wuxi.daos.GradeMapper.selectById"></association> </resultMap> <select id="selectStudentGradeById" resultMap="studentGradeById"> select * from student where id = #{id} </select> * 另一方 <select id="selectById" resultType="Grade"> select * from grade where id = #{id} </select> * 測試 Student student = smapper.selectStudentGradeById(4); System.out.println(student); // student.hashCode(); System.out.println(student.getGrade()); 2、一對多 * 一方 <resultMap type="Grade" id="gradeStudents"> <id column="id" property="id"></id> <result column="name" property="name"></result>
<!--關閉延遲載入會做兩次查詢--> <collection property="students" ofType="Student" column="id" select="com.wuxi.daos.StudentMapper.selectStudentsByGrade"></collection> </resultMap> <select id="selectById" resultMap="gradeStudents"> select * from grade where id = #{id} </select> * 多方 <select id="selectStudentsByGrade" resultType="Student"> select * from student where grade_id=#{grade_id} </select> * 測試 Grade grade = gmapper.selectById(1); System.out.println(grade); // student.hashCode(); System.out.println(grade.getStudents());
二、快取