Mybatis中联表查询(一对多)处理方式总结
作者:互联网
1、创建表格环境,mySql中的数据表格如下:
CREATE TABLE `teacher` ( `id` INT(10) NOT NULL, `name` VARCHAR(30) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=INNODB DEFAULT CHARSET=utf8 INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师'); CREATE TABLE `student` ( `id` INT(10) NOT NULL, `name` VARCHAR(30) DEFAULT NULL, `tid` INT(10) DEFAULT NULL, PRIMARY KEY (`id`), KEY `fktid` (`tid`), CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`) ) ENGINE=INNODB DEFAULT CHARSET=utf8INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1'); INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1'); INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1'); INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1'); INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
相关的表格对应关系如下:
一个老师对应多个学生
2、依据myBatis的官网搭建myBatis的测试环境
3、创建两个实体类
学生类
package com.liu.Pojo; import lombok.Data; @Data public class Student { private int id; private String name; private int tid; }
老师类
package com.liu.Pojo; import lombok.Data; import java.util.List; @Data public class Teacher { private int id; private String name; private List<Student> students; }
4、MyBatisUtils通用工具类
package com.liu.Utils; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; public class MyBatisUtils { //全局私有变量 private static SqlSessionFactory sqlSessionFactory = null; //加载数据库 static { String resource = "mybatis-config.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //获取相应的sqlSession对象 public static SqlSession getSqlSession(){ // 改为true后,则自动进行事务的提交 SqlSession sqlSession = sqlSessionFactory.openSession(true); return sqlSession; } }
5、mybatis-config.xml的配置(未设置日志)如下
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="db.properties"/> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <typeAliases> <package name="com.liu.Pojo"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/liu/Dao/StudentMapper.xml"/> </mappers> </configuration>
标签:name,private,查询,中联,tid,VALUES,Mybatis,import,id 来源: https://www.cnblogs.com/lhr123/p/16368066.html