Teacher(实体类)
package com.kuang.pojo;
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private int id;
private String name;
//一对多获取学生
List<Student> students;
}
teacherMapper
package com.kuang.dao;
import com.kuang.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface teacherMapper {
Teacher selectById(@Param("id") int id);
Teacher getTeacher(@Param("id") int id);
}
teacherMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.dao.teacherMapper">
<!-- 按结果嵌套查询 -->
<select id="selectById" resultMap="StudentTeacher">
select s.id sid, s.`name` sname, s.tid tid, t.id id, t.`name` tname
from student s,
teacher t
where s.tid = t.id
and t.id = #{id}
</select>
<resultMap id="StudentTeacher" 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="getTeacher" resultMap="StudentTeach">
select *
from teacher
where id = #{id}
</select>
<resultMap id="StudentTeach" type="Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" javaType="Arraylist" ofType="Student" column="id" select="select"/>
</resultMap>
<select id="select" resultType="Student">
select *
from student
where tid = #{id}
</select>
</mapper>
MybatisTest
package com.lisai;
import com.kuang.dao.teacherMapper;
import com.kuang.pojo.Teacher;
import com.kuang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MybatisTest {
@Test
public void Test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
teacherMapper mapper = sqlSession.getMapper(teacherMapper.class);
Teacher teacher = mapper.selectById(1);
System.out.println(teacher);
}
@Test
public void Test01(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
teacherMapper mapper = sqlSession.getMapper(teacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
}