Mybatis中的一对多关联查询

Mybatis中的一对多关联查询,第1张

Mybatis中的一对多关联查询 有两张表:

学生表:

教师表:

其关联关系可表示为:

在一对多查询时(一个老师对多个学生),可想到方法:

    子查询关联查询

将所需的教室和学生类构建好后,将mybatis核心配置完成后(所需的类和核心配置文件在文章末尾)
Mapper.xml文件可进行查询:

方式一:

    
        select * from mybatis.student;
    

    
        
        

        
    
    
    select  s.id sid ,s.name sname, t.name tname, t.id tid from mybatis.student s,mybatis.teacher t where  s.tid =t.id


    
        
        

        
            
        
    

注意:如果出现空则是老师id没有 查到,需要加上:

测试结果:

Student(id=1, name=小明, teacher=Teacher(id=0, name=秦老师))
Student(id=2, name=小红, teacher=Teacher(id=0, name=秦老师))
Student(id=3, name=小张, teacher=Teacher(id=0, name=秦老师))
Student(id=4, name=小李, teacher=Teacher(id=0, name=秦老师))
Student(id=5, name=小王, teacher=Teacher(id=0, name=秦老师)
测试所需的资源

核心配置文件:







    

    

        
    


    
        
    


    
        
            
            
                
                
                
                
            
        
    

    
        
    

核心封装类:

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession() {
        return  sqlSessionFactory.openSession();
    }
}

Student类:

@Data
public class Student {
    private  int id;
    private  String name;

    //学生需要关联一个老师
    private  Teacher teacher;
}

Teacher类:

@Data
public class Teacher {
    private int id;
    private String name;
}

TtudentMapper接口:

public interface TeacherMapper {

    @Select("select * from mybatis.teacher where id = #{tid}")
    Teacher getTeacher(@Param("tid") int id);
}

StudentMapper接口:

public interface StudentMapper {
    public List getStudent();
    public List getStudent2();
}

测试类:

public class Test {
    @Test
    public  void testStudent(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List studentList = mapper.getStudent();
        for (Student student : studentList) {
            System.out.println(student);
        }
        sqlSession.close();
    }

    @Test
    public  void testStudent2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List studentList = mapper.getStudent2();
        for (Student student : studentList) {
            System.out.println(student);
        }

        sqlSession.close();
    }
  }	

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5722523.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存