在 mybatis 的 配置 映射文件内
遇到 一对多和 多对多 表 的情况 应该 用 collection 标签
在 一对一的情况 应该 用 association 标签
一对多 多对多 映射文件配置
<mapper namespace="com.itheima.table02.OneToManyMapper">
<resultMap id="oneToMany" type="classes">
<id column="cid" property="id"/>
<result column="cname" property="name"/>
<collection property="students" ofType="student">
<id column="sid" property="id"/>
<result column="sname" property="name"/>
<result column="sage" property="age"/>
</collection>
</resultMap>
<select id="selectAll" resultMap="oneToMany">
SELECT c.id cid,c.name cname,s.id sid,s.name sname,s.age sage FROM classes c,student s WHERE c.id=s.cid;
</select>
</mapper>
mapper 根标签
namespace=“com.itheima.table02.OneToManyMapper”
跟标签的空间名称
作用:可以通过 找到对应的映射文件
空间名称与 代码接口 的全类名一致 就不用再去写 相关的实现类
resultMap 在有外键关联的其他表 用 resultMap 作 根标签 进行 表的列
与 代码相关的成员类对象中的成员变量进行绑定。
id=“oneToMany” 这个 resultMap 的 名字 与 select 标签 的 resultMap属性 的值 一致
就能将他们 关联起来
type=“classes” 这代码中成员类的名称,这么写是告诉程序,将关联的 select标签 中 的SQL语句 中的 表的名字 与 代码中的那个成员类对象关联。
id column="cid" property="id"
resultMap 的 子标签 id 是将 数据表中主键 id 与 代码成员类 中的 id 关联 column=“cid” 是数据库表中的主键 id property=“id” 代码对象中的 id。
result column="cname" property="name"
resultMap 的 子标签 result 是将 数据表中的其他列名 与 代码成员类 中的其他成员变量名 关联 column=“cname” 是数据库表中的其他列名 property="name"代码对象中的 其他成员变量名
collection property=“students” ofType=“student”
resultMap 的 子标签 collection 是将 数据表中设置 了一对多 的外键列 名 与 代码成员类对象中 用来 对应 这个外键列 的 成员变量 进行关联。
property=“students” 是 关联的 成员变量 的名字
ofType=“student” 是 关联的 成员变量的数据类型
外键关联的数据表 的 列名 都 要在 子标签 collection 里 进行与代码成员类对象的 量变 进行关联绑定
select id=“selectAll” resultMap=“oneToMany”
resultMap=“oneToMany” 这个 select 的 属性 与resultMap 标签 的 id 名 一致 就能将他们 关联起来 。
select id=“selectAll” id 要写成 与代码 持久层接口 相同的方法名 就能进行动态 代理。什么是动态代理呢?就是 将id 名 与 接口的方法名 写成 同一个名称 就不用 在写 持久层接口的实现类,
直接通过 持久层接口的名字.class 取接口的实现类对象
OneToOneMapper mapper = sqlSession.getMapper(OneToOneMapper.class);
用接口的实现类对象.持久层接口的方法名
就能使用 持久层接口的方法
通过 持久层接口的方法 找到映射配置文件 select标签中 id=“selectAll” 这个 sql 语句 ,
并在 通过 select标签中 resultMap=“oneToMany”
找到 resultMap标签中 id=“oneToMany”
通过 resultMap标签中 的关联配置 将数据库表中的列名 与 代码对象的成员变量名 关联起来
List<Card> list = mapper.selectAll();
mapper namespace=“com.itheima.table02.OneToManyMapper”
用 动态代理 也要 将 mapper跟标签 的空间名 写成 代码 持久层接口的 全类名。