N+1查询方式
[1]什么是N+1的查询方式
如果没有N+1的方式我们想要实现多表的查询,自己书写查询的业务逻辑代码(java)
mybatis希望通过自己标签配置的方式来解决这个问题
[2]执行的操作
查询学生所在班级的信息(一对一)
查询班级中所有学生的信息(一对多)
使用的时候书写标签需要注意:
查询出来返回的是一个对象:association
查询出来返回的是一个集合:collection
总结: 业务装配方式和N+1查询方式共同点:执行SQL语句的条数上都是N+1条语句不同点:业务装配方式:是我们自己书写java代码的方式进行配置的N+1方式:通过MyBatis标签配置的方式实现的
接口
StudentMapper.java
public interface StudentMapper {//查询所有学生的操作List<Student> selectAll();List<Student> selectMore(int clazzno);
}
ClazzMapper.java
public interface ClazzMapper {//查询指定学生所在班级的信息Clazz selectOne(int clazzno);//查询所有班级信息List<Clazz> selectAll();
}
XML
StudentMapper.xml
<select id="selectAll" resultMap="rm1">SELECT * from student</select><resultMap id="rm1" type="student"><!--column:数据库的列名 property:实体的属性名--><!--如果数据库的列明和实体类中的属性名一致,就可以省去该标签但是公共字段不建议省去--><id column="sid" property="sid"></id><result column="sname" property="sname"></result><result column="clazzno" property="clazzno"></result><!--select * from clazz where clazzno=?select:执行哪一个方法column:希望查询的哪一列作为参数进行传递javaType:返回值类型property:把返回的结果赋值给对象中哪一个属性--><association select="com.bjsxt.mapper.ClazzMapper.selectOne"column="clazzno" javaType="clazz" property="cla"></association></resultMap>
ClazzMapper.xml
<select id="selectAll" resultMap="rm1">SELECT * from clazz</select><resultMap id="rm1" type="clazz"><id column="clazzno" property="clazzno"></id><result column="cname" property="cname"></result><!--select:调用哪一个xml中方法column:希望那一列作为参数进行传递ofType:集合的泛型property:把返回的数据整体赋值给哪一个属性--><collection select="com.bjsxt.mapper.StudentMapper.selectMore"column="clazzno" ofType="student" property="li"></collection></resultMap>
测试
//[4]执行方法StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);ClazzMapper claMapper = sqlSession.getMapper(ClazzMapper.class);//查询所有学生所在的班级的信息/*List<Student> list = stuMapper.selectAll();for(Student stu:list){System.out.println(stu);}*///查询所有班级中学生的信息List<Clazz> list = claMapper.selectAll();for(Clazz clazz:list){System.out.println(clazz);}