XML 映射器
多对一:关联(association)
一对多:集合(collection)
mysql 创建教师、学生表,插入数据
create table `teacher`(id int(10) primary key,`name` varchar(30) default null
) 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=utf8;insert into student (id,`name`,tid) values (1,'学生1',1);
insert into student (id,`name`,tid) values (2,'学生2',1);
insert into student (id,`name`,tid) values (3,'学生3',1);
pom.xml 导入相应 jar 包
<dependencies><!-- mysql驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency><!-- mybatis驱动 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.16</version></dependency><!-- junit驱动 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version></dependency><!-- lombok驱动 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.34</version></dependency></dependencies><!-- 在build中配置resources,防止资源导出失败 --><build><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include><include>**/*.properties</include></includes></resource><resource><directory>src/main/resources</directory><includes><include>**/*.xml</include><include>**/*.properties</include></includes></resource></resources></build>
resources 目录下创建 db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=root
resources 目录下创建 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><!-- configuration核心配置文件 -->
<configuration><!-- 引入外部配置文件 --><properties resource="db.properties"/><settings><!-- 日志工厂实现 --><setting name="logImpl" value="STDOUT_LOGGING"/></settings><!-- 扫描实体类的包 --><typeAliases><package name="com.demo.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 class="com.demo.dao.TeacherMapper"/><mapper class="com.demo.dao.StudentMapper"/></mappers></configuration>
MybatisUtils 工具类:
package com.demo.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;static {try {//获取sqlSessionFactory对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {e.printStackTrace();}}/*有了SqlSessionFactory,就可以获得SqlSession的实例SqlSession提供了在数据库执行SQL命令所需的所有方法可以通过SqlSession实例来执行已映射的SQL语句*/public static SqlSession getSqlSession(){return sqlSessionFactory.openSession(true);}
}
实体类与表字段一致
Teacher 类:
package com.demo.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {private int id;private String name;
}
Student 类:
(因为 tid 设置了外键,直接写 int tid 则无法关联,所以通过组合的方式关联进来)
package com.demo.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {private int id;private String name;//多个学生关联一个老师private Teacher teacher;
}
TeacherMapper 接口:
import com.demo.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;public interface TeacherMapper {@Select("select * from teacher where id = #{tid}")Teacher getTeacher(@Param("tid") int id);
}
同理,写个 StudentMapper 接口
resources 目录创建同包名
TeacherMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.demo.dao.TeacherMapper"></mapper>
同理,创建 StudentMapper.xml
在核心配置文件 mybatis-config.xml 绑定注册:
<mappers><mapper class="com.demo.dao.TeacherMapper"/><mapper class="com.demo.dao.StudentMapper"/></mappers>
测试类:
package com.demo.dao;import com.demo.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;public class MyTest {@Testpublic void test(){SqlSession sqlSession = MybatisUtils.getSqlSession();TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);System.out.println(mapper.getTeacher(1));sqlSession.close();}
}
输出结果:
测试环境搭建步骤:
1.导入 Lombok 依赖
2.新建实体类 Teacher、Student
3.建立 Mapper 接口
4.建立 Mapper.xml 文件
5.在核心配置文件中绑定注册 Mapper 接口或者文件
6.测试查询是否成功
多对一处理:
StudentMapper 实体类:
package com.demo.dao;import com.demo.pojo.Student;import java.util.List;public interface StudentMapper {//查询所有学生信息,以及对应教师信息List<Student> getStudent();
}
方法一:查找嵌套,根据查询出来的学生 tid,寻找对应的教师
StudentMapper.xml:
关联:association
集合:collection
javaType:对象类型
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.demo.dao.StudentMapper"><select id="getStudent" resultMap="tid">select * from student</select><resultMap id="tid" type="student"><result column="id" property="id"/><result column="name" property="name"/><!-- 关联:association --><!-- 集合:collection --><!-- javaType:对象类型 --><association property="teacher" column="tid" javaType="teacher" select="getTeacher"/></resultMap><select id="getTeacher" resultType="teacher">select * from teacher where id = #{tid}</select>
</mapper>
association 关联的 property 是 Student 类的组合
测试类:遍历数组
package com.demo.dao;import com.demo.pojo.Student;
import com.demo.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.List;public class MyTest {@Testpublic void getStudent(){SqlSession sqlSession = MybatisUtils.getSqlSession();StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);List<Student> studentList = mapper.getStudent();for(Student student : studentList){System.out.println(student);}sqlSession.close();}
}
运行结果如下:
方法二:结果嵌套
StudentMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.demo.dao.StudentMapper"><select id="getStudent" resultMap="tid">select s.id sid,s.name sname,s.tid stid,t.name tname from student s,teacher t where s.tid = t.id;</select><resultMap id="tid" type="Student"><result property="id" column="sid"/><result property="name" column="sname"/><association property="teacher" javaType="Teacher"><result property="name" column="tname"/><result property="id" column="stid"/></association></resultMap>
</mapper>
结果如下:
Mybatis 多对一查询方式:
1.子查询
2.联表查询
一对多处理:
Student 类:
package com.demo.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {private int id;private String name;private int tid;
}
Teacher 类:
package com.demo.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.util.List;@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {private int id;private String name;//一名教师教导多名学生private List<Student> students;
}
TeacherMapper 接口:
package com.demo.dao;import com.demo.pojo.Teacher;
import org.apache.ibatis.annotations.Param;import java.util.List;public interface TeacherMapper {List<Teacher> getTeacher();//获取指定教师下所有学生及教师的信息Teacher getTeacherById(@Param("tid") int id);
}
TeacherMapper.xml:
方法一:结果嵌套查询
javaType 指定属性的类型,ofType 应用于集合中的泛型信息
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.demo.dao.TeacherMapper"><select id="getTeacher" resultType="teacher">select * from teacher</select><!-- 结果嵌套查询 --><!-- resultMap 结果集映射 --><select id="getTeacherById" resultMap="TeacherStudent">select s.id sid,s.name sname,t.name tname,t.id tidfrom student s,teacher twhere s.tid = t.id and t.id = #{tid};</select><resultMap id="TeacherStudent" type="teacher"><result property="id" column="tid"/><result property="name" column="tname"/><!-- 集合:collection --><!-- javaType指定属性的类型,ofType应用于集合中的泛型信息 --><collection property="students" ofType="student"><result property="id" column="sid"/><result property="name" column="sname"/><result property="tid" column="tid"/></collection></resultMap>
</mapper>
测试类:
package com.demo.dao;import com.demo.pojo.Teacher;
import com.demo.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;public class MyTest {@Testpublic void getTeacher(){SqlSession sqlSession = MybatisUtils.getSqlSession();TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);for (Teacher teacher : mapper.getTeacher()) {System.out.println(teacher);}sqlSession.close();}@Testpublic void getTeacherById(){SqlSession sqlSession = MybatisUtils.getSqlSession();TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);System.out.println(mapper.getTeacherById(1));sqlSession.close();}
}
运行结果:
方法二:查询嵌套
<select id="getTeacherById" resultMap="TeacherStudent">select * from teacher where id = #{tid}</select><resultMap id="TeacherStudent" type="teacher"><collection property="students" javaType="ArrayList" ofType="student" select="tid" column="id"/></resultMap><select id="tid" resultMap="student">select * from student where tid = #{tid}</select>
总结:
1.关联:association(多对一)
2.集合:collection(一对多)
3. javaType 用来指定实体类中属性的类型
4. ofType 用来指定映射到 List 或集合中的 pojo 类型,泛型中的约束类型
注意点:
1.保证 SQL 可读性
2.注意一对多或多对一属性名和字段
3.使用 Log4j 日志排查错误
综上,还需了解 Mysql 引擎、InnoDB 底层原理、索引、索引优化等