MyBatis的一对多关联关系(注解形式)

399人浏览 / 0人评论
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 selectByClazzId(Integer clazz_id);
}
2、引入映射接口
    
        
        
    
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();
    }
}

全部评论

晴天下起了小雨
2017-10-01 18:00
很喜欢,果断关注了
wjmyly7336064
2017-10-01 18:00
相当实用,赞美了
橘大佬
2017-10-01 18:00
就是有些细节再到位点就好了…