Mybatis_动态sql_多表联查

Mybatis_动态sql 多表联查

动态SQL

使用方式:在mapper映射文件中加where标签配合if标签使用

使用效果:在有条件时按照条件查询,没有条件查询全部

where标签作用

当有查询条件时会自动加where关键字,如果没有查询条件就自动忽略,配合if标签(当有多个条件时,Mybatis会帮我们省略中第一个连接关键字)

多表联查

在实际项目开发中,如果使用的数据不能使用domain完全覆盖,这时我们有两种解决方案:

  • 使用map接收

    如果是临时数据(使用的重复率不高使用map)

  • 创建vo接收

    使用重复率高的话就建立一个vo类用于覆盖所有要使用的数据属性

两个表之间建立外键(一对多),在多的表中建立外键(关系上为外键,实际表中不建立外键)

两个表:

  • 学生Student表
  • 城市City表

需求:

  1. 查询出学生名称和城市名称
  2. 查询出学生和城市所有信息,加vo
  3. 查询出年龄小于20的学生和城市所有信息

查询出学生名称和城市名称

查询出学生和城市所有信息,加vo

查询出年龄小于20的学生和城市所有信息

环境:Spring集成Mybatis

代码:

vo

package com.geekrose.vo;

/**
 * @author Joker_Dong
 * @date 2021-11-11 21:49
 */

public class StudentAndCity {
    private Integer sid;
    private String sname;
    private String semail;
    private Integer sage;
    private Integer cid;
    private String cname;
    private Integer pid;
    // get set toString
}

接口

public interface MultiTable {


    // 查询 学生名称和城市名称
    List> selectBothName();

    // 查询 学生和城市的全部信息
    List selectAll();

    // 查询所有学生年龄小于20 的学生和城市信息
    List selectAge(Integer age);

}

Mapper文件




    
    

    

    


测试

@Test
public void testSelectAge(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    MultiTable dao = context.getBean("multiTable", MultiTable.class);
    List studentAndCities = dao.selectAge(20);
    for (StudentAndCity studentAndCity:studentAndCities){
        System.out.println(studentAndCity);
    }
}

结果

StudentAndCity{sid=1003, sname='伍六七', semail='[email protected]', sage=18, cid=1, cname='沈阳', pid=1}
StudentAndCity{sid=1004, sname='梅花十三', semail='[email protected]', sage=17, cid=2, cname='大连', pid=1}

你可能感兴趣的:(Mybatis_动态sql_多表联查)