关联Association 多对一通俗来讲,就是一个班里的学生对应一个班主任,也就是有关联
集合 collection 一对多--一个班主任对应全班学生,这叫集合。
上例子,举例子就明白了
一、一对多
建立学生类(id,name,tid),教师类(id,name)学生类中的tid关联教师类的id,进行实例化
(如果想偷懒用lombok,@data方法可以解决)。
public class Student {
private int id;
private String name;
//每个学生关联
private int tid;
}
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student>students;
}
在teacherMapper的接口里面写入方法,供测试调用
Teacher getTeacher(@Param("tid")int id);
紧接着在teacherMapper.xml进行配置文件,并写入SQL语句
<select id="getTeacher" 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>
最后写入Test方法测试
@Test
public void Test(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
点击运行即可成功,这也就是咱们所说的一对多,集合,产生一个集合。
二、多对一也是如此
建立实体类
@Data
public class Student {
private int id;
private String name;
//每个学生关联
private Teacher teacher;
}
@Data
public class Teacher {
private int id;
private String name;
}
写个学生接口,反射学生
public interface StudentMapper {
//查询学生信息及对应相应老师的信息
public List<Student> getStudent();
}
紧接着在studentMapper.xml注册
<select id="getStudent" resultMap="StudentTeacher">
select s.id sid,s.name sname,t.name tname
from student s ,teacher t
where s.tid=t.id;
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
然后编写测试方法
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtil.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
Javatype 用来指定实体类中属性的 类型
Oftype 用来指定映射到List或者集合中的entity类型,泛型中的约束类型