项目环境:
开发环境:IntelliJ IDEA 2019.3.1 ,JDK1.8 ,MySQL: 5.6.47
采用远程数据库连接:使用ailiyun ESC CentOS 7.0项目技术:
学会使用mybatis-generator自动部署代码
学会使用tk.mybatis插件进行数据库的操作
学会实现父子表管子查询
项目资源连接:示例源代码
本项目采用mybatis-generator的自动生成插件和Tk插件结合,实现对父子表的联合查询,使返回结果包括父表信息和它的子表每个子数据信息。
schooldb
使用Navicat创建数据库schooldb
,并运行下面的sql文件
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for tbl_student
-- ----------------------------
DROP TABLE IF EXISTS `tbl_student`;
CREATE TABLE `tbl_student` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`teacher_id` bigint(20) NULL DEFAULT NULL,
`name` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '学生姓名',
`age` int(11) NULL DEFAULT NULL COMMENT '年龄',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Compact;
-- ----------------------------
-- Records of tbl_student
-- ----------------------------
INSERT INTO `tbl_student` VALUES (1, 1, '小明', 15);
INSERT INTO `tbl_student` VALUES (2, 1, '小李', 15);
INSERT INTO `tbl_student` VALUES (3, 1, '小红', 14);
INSERT INTO `tbl_student` VALUES (4, 2, '小李', 14);
INSERT INTO `tbl_student` VALUES (5, 2, '王二', 15);
INSERT INTO `tbl_student` VALUES (6, 2, '张三', 13);
-- ----------------------------
-- Table structure for tbl_teacher
-- ----------------------------
DROP TABLE IF EXISTS `tbl_teacher`;
CREATE TABLE `tbl_teacher` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '老师姓名',
`age` int(11) NULL DEFAULT NULL COMMENT '老师年龄',
`phone` int(11) NULL DEFAULT NULL COMMENT '手机号',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Compact;
-- ----------------------------
-- Records of tbl_teacher
-- ----------------------------
INSERT INTO `tbl_teacher` VALUES (1, '王老师', 45, 1596369856);
INSERT INTO `tbl_teacher` VALUES (2, '李老师', 32, 1358948956);
SET FOREIGN_KEY_CHECKS = 1;
<dependencies>
<dependency>
<groupId>tk.mybatisgroupId>
<artifactId>mapper-spring-boot-starterartifactId>
<version>2.0.4version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.1version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.10version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
<version>5.1.6version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<exclusions>
<exclusion>
<groupId>org.junit.vintagegroupId>
<artifactId>junit-vintage-engineartifactId>
exclusion>
exclusions>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
<plugin>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-maven-pluginartifactId>
<version>1.3.7version>
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
<version>5.1.6version>
dependency>
<dependency>
<groupId>tk.mybatisgroupId>
<artifactId>mapperartifactId>
<version>4.1.5version>
dependency>
dependencies>
<configuration>
<configurationFile>${basedir}/src/main/resources/mybatis-generator.xmlconfigurationFile>
<overwrite>trueoverwrite>
<verbose>trueverbose>
configuration>
plugin>
plugins>
build>
application.properties
#远程数据库连接
spring.datasource.url=jdbc:mysql://121.40.83.80:3306/schooldb?characterEncoding=UTF-8&useSSL=false
#数据库用户名
spring.datasource.username=alvin
#数据库密码
spring.datasource.password=123456
#数据源类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
mybatis.mapper-locations=classpath:/mapper/*.xml
Tk
在utils包下 创建TkMapper.java类
/**
* 继承
* @param
*/
public interface TkMapper<T> extends Mapper<T>, MySqlMapper<T> {
//特别注意,该接口不能被扫描到,否则会出错
}
mybatis-generator.xml
<generatorConfiguration>
<properties resource="application.properties"/>
<context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="com.alvin.mybatis.utils.TkMapper"/>
<property name="caseSensitive" value="true"/>
<property name="forceAnnotation" value="true"/>
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
plugin>
<commentGenerator>
<property name="suppressDate" value="true" />
<property name="suppressAllComments" value="false" />
commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://121.40.83.80:3306/schooldb"
userId="alvin"
password="123456">
jdbcConnection>
<javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">
<property name="forceBigDecimals" value="false"/>
javaTypeResolver>
<javaModelGenerator targetPackage="com.alvin.mybatis.model" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="constructorBased" value="true"/>
<property name="trimStrings" value="true"/>
<property name="immutable" value="false"/>
javaModelGenerator>
<sqlMapGenerator targetPackage="mybatis" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
sqlMapGenerator>
<javaClientGenerator targetPackage="com.alvin.mybatis.mapper" type="XMLMAPPER" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
javaClientGenerator>
<table tableName="tbl_student" domainObjectName="Student" enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
<generatedKey column="id" sqlStatement="JDBC" identity="true"/>
table>
<table tableName="tbl_teacher" domainObjectName="Teacher" enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
<generatedKey column="id" sqlStatement="JDBC" identity="true"/>
table>
<table tableName="tbl_teacher_student" domainObjectName="TeacherStudent" enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
<generatedKey column="id" sqlStatement="JDBC" identity="true"/>
table>
context>
generatorConfiguration>
这里需要在启动类加入一个注解@MapperScan(basePackages = "com.alvin.mybatis.mapper")
,注意它的引包是import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
//com.alvin.mybatis.mapper是我们扫描.mapper的地址
@MapperScan(basePackages = "com.alvin.mybatis.mapper")
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
}
public class StudentDto {
private Long id;
private String name;
private Integer age;
private Long teacherId;
//省略setter/getter方法
}
public class TeacherDto {
private Long id;
private String name;
private Integer age;
private Integer phone;
private List<StudentDto> dtoList;
//省略setter/getter方法
}
@Controller
public class TestController {
@Autowired
TestService testService;
@ResponseBody
@GetMapping("/test")
public List<TeacherDto> search(
@RequestParam Long id
){
return testService.search(id);
}
}
@Service
public class TestService {
@Autowired
StudentMapper studentMapper;
@Autowired
TeacherMapper teacherMapper;
public List<TeacherDto> search(Long id){
List<TeacherDto> repList = new ArrayList<>();
TeacherDto teacherDto = new TeacherDto();
//查询该老师的所有信息
Teacher teacher = teacherMapper.selectByPrimaryKey(id);
BeanUtils.copyProperties(teacher,teacherDto);
repList.add(teacherDto);
//查询该老师的所有学生
Example example = new Example(Student.class);
example.createCriteria().andEqualTo("teacherId",id);
List<Student> students = studentMapper.selectByExample(example);
//查询每个学生的个人信息
List<StudentDto> studentDtoList = new ArrayList<>();
for(Student student : students){
StudentDto studentDto = new StudentDto();
BeanUtils.copyProperties(student,studentDto);
studentDtoList.add(studentDto);
teacherDto.setDtoList(studentDtoList);
}
return repList;
}
}
也可以根据java8的特性使用stream代替for迭代
@Service
public class TestService {
@Autowired
StudentMapper studentMapper;
@Autowired
TeacherMapper teacherMapper;
public List<TeacherDto> search(Long id){
List<TeacherDto> repList = new ArrayList<>();
TeacherDto teacherDto = new TeacherDto();
//查询该老师的所有信息
Teacher teacher = teacherMapper.selectByPrimaryKey(id);
BeanUtils.copyProperties(teacher,teacherDto);
repList.add(teacherDto);
//查询该老师的所有学生
Example example = new Example(Student.class);
example.createCriteria().andEqualTo("teacherId",id);
List<Student> students = studentMapper.selectByExample(example);
//查询每个学生的个人信息
List<StudentDto> list = students.stream().map(student -> {
StudentDto studentDto = new StudentDto();
BeanUtils.copyProperties(student, studentDto);
return studentDto;
}).collect(Collectors.toList());
teacherDto.setDtoList(list);
return repList;
}