首先搭建学习环境
创建两张表,老师表和学生表
学生的tid是外键,依赖老师的id。
然后编写基本的配置文件
学生实体类:
package com.dongmu.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private Teacher teacher;
}
老师实体类:
package com.dongmu.pojo;
import lombok.Data;
@Data
public class Teacher {
int id;
String name;
}
然后查询学生,并输出对应的老师。这时候就会出现问题,因为老师是引用数据类型
mapper文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dongmu.dao.StudentDao">
<select id="getAllSutdents" resultType="Student">
select s.*,t.name as teacher from student s,teacher t where s.tid = t.id
</select>
</mapper>
查询结果
使用resultMap的associate指定结果的类型
<select id="getAllSutdents2" resultMap="map2">
select s.id,s.name,t.name as tname from student s,teacher t where s.tid = t.id
</select>
<resultMap id="map2" type="Student">
<result column="id" property="id"/>
<result column="name" property="name"/>
<association property="teacher" javaType="Teacher">
<result column="tname" property="name"/>
<result column="s.id" property="id"/>
</association>
</resultMap>
下面介绍一对多的方法
dao接口:
package com.dongmu.dao;
import com.dongmu.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface TeacherDao {
public List<Teacher> getAllTeacher(@Param("tid") int id);
public List<Teacher> getAllTeacher2(@Param("tid") int id);
}
mapper文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dongmu.dao.TeacherDao">
按照查询嵌套处理
<select id="getAllTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname, t.name tname ,t.id tid
from student s ,teacher t
where 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 property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
按照结果嵌套处理
<select id="getAllTeacher2" resultMap="Teacher2">
select * from teacher where id=#{tid}
</select>
<resultMap id="Teacher2" type="Teacher">
<result column="id" property="id"/>
<result column="name" property="name"/>
<collection property="students" javaType="ArrayList" ofType="Student" column="id" select="selectstu">
</collection>
</resultMap>
<select id="selectstu" resultType="Student">
select * from student where tid=#{id}
</select>
</mapper>
javaType指定实体类中属性的类型
ofType:用来指定集合映射到List或者集合中的类型,(泛型中的约束类型)
注意慢sql问题,要注意sql的效率问题。