栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

mybatis学习04-多对一和一对多查询-动态sql

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

mybatis学习04-多对一和一对多查询-动态sql

mybatis 学习04 多对一 查询
  • 实体类
//teacher
@Data
public class Teacher {
    private int id;
    private String name;
}
//student
@Data
public class Student {
    private int id;
    private String name;
    private Teacher teacher;  //注意此处,需要查出一个对象
}
  • StudentMapper.interface
public interface StudentMapper {
    //查询所有学生所关联的老师 association
    public List getStudent();
}
  • StudentMapper.xml

    
    
        
        

          //此处的javatype对应的就是																				Teacher类型
            
            
        

    

    
          SELECT s.id sid,s.name sname,t.id tid,t.name tname from
          student s,teacher t WHERe s.tid =t.id
    
    

  • 测试
public void getStudent() {
        SqlSession sqlSession= myBatisUtil.getSession();

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        List list = mapper.getStudent();
        for (Student student : list) {
            System.out.println(student);
        }
        sqlSession.close();
}
  • 结果
Student(id=1, name=小明, teacher=Teacher(id=1, name=xpc))
Student(id=2, name=小红, teacher=Teacher(id=1, name=xpc))
Student(id=3, name=小张, teacher=Teacher(id=1, name=xpc))
Student(id=4, name=小李, teacher=Teacher(id=1, name=xpc))
Student(id=5, name=小王, teacher=Teacher(id=1, name=xpc))
一对多查询
  • 实体类
//student
@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}
//teacher
@Data
public class Teacher {
    private int id;
    private String name;
    private List students;  //此处是一个student list集合
}
  • 接口TeacherMapper.interface
public interface TeacherMapper {
    //查询一个指定的老师带的所有学生 collection
    public Teacher getTeacher(@Param("tid") int id);
}
  • TeacherMapper.xml


    
        SELECT * from mybatis.blog  //注意此处的where标签是为了不用where 1=1
        
            
                and title=#{title}
            
            
                and author=#{author}
            
        
    
  • 测试
@org.junit.Test
    public void test() {
        SqlSession sqlSession=myBatisUtil.getSession();

        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        HashMap map = new HashMap();
        //map.put("title","Mybatis"); //
        map.put("author", "狂神说");

    	//情况1:当map为空的时候查询出全部博客
    	//情况2:当title不为空的时候,查询出对应title的博客
    	//情况3:当title为空author不为空的时候,查询出对应author的全部博客
        List list=mapper.getBlogs(map);
        for (Blog blog : list) {
            System.out.println(blog);
        }

        sqlSession.close();
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/310326.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号