Mybatis实现多对一sql association
MySql中实现多对一??????
创建一个数据库叫mybatis
创建一个student表
create table mybatis.student ( sid int not null primary key, sname varchar(30) not null, tid int not null, constraint student_ibfk_1 foreign key (tid) references mybatis.teacher (tid) );
该表中 sid为主键 tid为外键
sql中数据
创建一个teacher表
create table mybatis.teacher ( tid int not null primary key, tname varchar(30) null, constraint teacher_tname_uindex unique (tname) );
该表中tid为主键
sql中数据
根据学生的信息获取老师信息,每个老师对应多个学生,学生只对应一个老师
查询sql语句
select sid,sname,tname from student s, teacher t where s.tid = t.tid;
查询结果
Mybatis使用association语句实现多对一??????
方法一:子查询
studentMapper.xml配置
<select id="getStudentTeacherList01" resultMap="studentTeacher"> select * from student; select> <resultMap id="studentTeacher" type="student"> <association property="t" column="tid" javaType="teacher" select="getTeacher"/> resultMap> <select id="getTeacher" parameterType="int" resultType="teacher"> select * from teacher where tid = #{tid}; select>
方法二:连表查询
studentMapper.xml配置
<select id="getStudentTeacherList02" resultMap="st"> select sid, sname, tname from student s, teacher t where s.tid = t.tid; select> <resultMap id="st" type="student"> <association property="t" javaType="teacher"> <result property="tname" column="tname"/> association> resultMap>