关联 association 多对一
问题的出现 、、、
当我们需要查询多张表时,我们有两种大的方式选择
第一就是用映射
接口
//查询所有Edu_comment
List<Edu_comment> getIdEdu();
Mapper
<select id="getIdEdu" parameterType="map" resultMap="educom">
select c.id cid, c.gmt_modified cgm ,c.teacher_id tid
from guli_edu.edu_comment c ,guli_edu.edu_teacher t
</select>
<resultMap id="educom" type="edu_comment">
<result property="id" column="cid"/>
<result property="gmt_modified" column="cgm"/>
<!-- 对象类型用 association ;-->
<!-- 集合类型用 collection JavaType和ofType都是用来指定对象类型的,但是-->
<!--JavaType是用来指定pojo中属性的类型,而ofType指定的是 映射到list集合属性中pojo的类型-->
<!--<association property="tid" javaType="Teacher" property 代表实体类中 属性的名称(即对象的属性名称)> -->
<association property="tid" javaType="Edu_teacher">
<result property="id" column="tid"/>
</association>
</resultMap>
测试
@Test
public void test03(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
Edu_ctMapper mapper = sqlSession.getMapper(Edu_ctMapper.class);
List<Edu_ct> allEdu = mapper.getAllEdu();
for (Edu_ct use:allEdu){
System.out.println(use);
}
}
注意点
还有一中方法 就是 把多表联查的 sql写出来先
SELECT c.id cid,c.`content` cc,c.teacher_id ctid ,t.id tid ,t.name tname
FROM guli_edu.edu_comment c INNER JOIN guli_edu.edu_teacher t
WHERE t.id=c.teacher_id
然后建立一个实体类 这个类的属性就是这个sql语句中要查询的列的别名
package com.mumu.pojo;
import lombok.Data;
@Data
public class Edu_ct {
private String cid;
private String cc;
private String ctid;
private String tname;
private String tid;
}
然后编写接口
List<Edu_ct> getAllEdu();
Mapper
<mapper namespace="com.mumu.dao.Edu_ctMapper">
<select id="getAllEdu" resultType="edu_ct">
SELECT c.id cid,c.`content` cc,c.teacher_id ctid ,t.id tid ,t.name tname
FROM guli_edu.edu_comment c INNER JOIN guli_edu.edu_teacher t
WHERE t.id=c.teacher_id
</select>
<!-- SELECT c.id cid,c.`content` cc ,t.id tid ,t.name tname
FROM guli_edu.edu_comment c JOIN guli_edu.edu_teacher t-->
</mapper>
注意 mapper是 新建实体类
<mapper namespace=“com.mumu.dao.Edu_ctMapper”
…