1、映射接口

  • public interface ClazzMapper
  • {
  • // 根据id查询班级信息
  • @Select("SELECT * FROM tb_clazz WHERE ID = #{id}")
  • @Results(
  • { @Result(id = true, column = "id", property = "id"), @Result(column = "code", property = "code"),
  • @Result(column = "name", property = "name"),
  • @Result(column = "id", property = "students", many = @Many(select = "cn.mybatis.mydemo5.mapper.StudentMapper.selectByClazzId", fetchType = FetchType.LAZY)) })
  • Clazz selectById(Integer id);
  • }
  • public interface StudentMapper
  • {
  • // 根据班级id查询班级所有学生
  • @Select("SELECT * FROM tb_student WHERE CLAZZ_ID = #{id}")
  • @Results(
  • { @Result(id = true, column = "id", property = "id"), @Result(column = "name", property = "name"),
  • @Result(column = "sex", property = "sex"), @Result(column = "age", property = "age") })
  • List<Student> selectByClazzId(Integer clazz_id);
  • }

2、引入映射接口

  • <mappers>
  • <mapper class="cn.mybatis.mydemo5.mapper.ClazzMapper" />
  • <mapper class="cn.mybatis.mydemo5.mapper.StudentMapper" />
  • </mappers>

3、测试代码

  • public class App
  • {
  • public static void main(String[] args) throws Exception
  • {
  • // 获取Session实例
  • SqlSession session = MySqlSessionFactory.getSqlSession();
  • // 获取ClazzMapper实例
  • ClazzMapper cm = session.getMapper(ClazzMapper.class);
  • // 根据id查询Clazz对象
  • Clazz clazz = cm.selectById(1);
  • // 查看查询到的Clazz对象
  • System.out.println(clazz.getId() + " " + clazz.getCode() + " " + clazz.getName());
  • // 查看关联的学生集合,因为配置使用的是LAZY懒加载,所以当使用时才执行SQL语句
  • clazz.getStudents().forEach(student -> System.out.println(student));
  • // 提交事务
  • session.commit();
  • // 关闭Session
  • session.close();
  • }
  • }

标签: none

仅有一条评论

  1. 闵亨强 闵亨强

    诚恳拜师

添加新评论