这篇博客我想写下Mybatis 多表关联查询中的一对一、 一对多查询。
这里我用到了三个表 一个是班级表class 、一个是老师表teacher 、一个是学生表student 以下是它们的字段
首先是班级表:
其次是老师表:
最后是学生表:
其中班级表中得teacher_id字段是 老师表的外建
其中学生表中得class_id 字段是班级表的外键
首先是一对一:
它用到了两个表 班级表和老师表
首先是sql编写
<!-- 一对一 -->
<resultMap type="_Classes" id="ClassOfResultMap">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<!-- 用于一对一 -->
<association property="teacher" javaType="_Teacher">
<id property="tId" column="t_id" />
<result property="tName" column="t_name" />
</association>
</resultMap>
<!-- 例子 -->
<select id="selectOfClass" parameterType="int" resultMap="ClassOfResultMap">
select * from class a,teacher b where a.teacher_id=b.t_id
</select>
这里我简单讲下我对Mybatis一对一的理解 。首先是 <resultMap></resultMap>的编写,它是以有外键字段的那个表为主体 。<association property=“teacher”></association> 就相当于一对一的关键字 property的属性值相对应的便是实体类的属性(外键字段)
其次便是接口的编写:
public List selectOfClass();
最后便是测试类
public class ClassTest {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("conf.xml");
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is);
SqlSession ss = ssf.openSession();
//关联查询
List s = ss.selectList("com.mapping.ClassMapper.selectOfClass");
System.out.println(s);
ss.commit();
ss.close();
}
}
一对多:
他用到的两个表是 班级表和学生表
首先是SQL语句
<!-- 一对多 -->
<resultMap type="_Classes" id="StudentOfResultMap">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<!-- 由于一对多 -->
<collection property="students" ofType="_Student">
<id property="id" column="s_id"/>
<result property="name" column="s_name"/>
</collection>
</resultMap>
<!-- 例子 -->
<select id="selectOfStudent" parameterType="int" resultMap="StudentOfResultMap">
select * from class a,student b where a.c_id=b.class_id and class_id = #{students}
</select>
其次是 接口:
public List selectOfStudent(int id);
测试类:
public class ClassTest {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("conf.xml");
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is);
SqlSession ss = ssf.openSession();
List s = ss.selectList("com.mapping.ClassMapper.selectOfStudent",1);
System.out.println(s);
ss.commit();
ss.close();
}
}
对于 Mybatis 的一对一、一对多 我就写到这里.
但是在这里我要说一点:因为我写的这三篇博客主要是针对于后台简单测试,因此在接口编写的时候很随意,并没有在接口编写的时候参数并没有填写。
当你在做练习的时候可自行添加。