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)坚持系统化的学习方式,由量变到质变。仅仅解决工作中的问题,并不叫系统化的学习。

(2)坚持以价值为导向的学习方式,扔掉低价值知识[配置、调参、安装],聚焦高价值知识[结构、算法、优化],推动量变到质变的进程。

添加新评论