第3.121课 上课 MyBatis3关联介绍, 多对一关联(associatio…

3_121

MyBatis3关联介绍

 多对一关联(association映射)

  结构图

   图1

   图2

  定义实体类

   Province.java

   City.java

  在xxxMapper.xml中配置表之间的多对一关系

   ProvinceMapper.xml

   CityMapper.xml

 

  配置XxxMapper.xml

  执行查询

1.获取SqlSession对象。

 

2.执行查询。

 一对多关联(collection映射)

<!-- 结果集映射 -->

<resultMap type="province" id="baseResultMap" autoMapping="true">

<!-- 省份为一的一端用collection进行配置

property: 属必名

column : 列名

ofType : 集合中的元素类型

javaType : java类型

select : 查询(命名空间.select标签的id属性值)

-->

<collection property="cities" column="id" ofType="city" javaType="list"

select="com.yayadou.mapper.CityMapper.get"/>

</resultMap>

  定义实体类

   City.java

   Province.java

  在xxxMapper.xml中配置表之间的多对一关系

   CityMapper.xml

 

   ProvinceMapper.xml

  配置XxxMapper.xml

  执行查询

1.获取SqlSession对象。

 

2.执行查询。

 多对多关联映射(collection映射)

StudentMapper.xml文件:

<!-- 结果集映射 -->

<resultMap type="Student" id="baseResultMap" autoMapping="true">

<!-- 集合用collection进行配置

property: 属必名

column : 列名

ofType : 集合中的元素类型

javaType : java类型

select : 查询(命名空间.select标签的id属性值)

-->

<collection property="teachers" column="id" ofType="Teacher" javaType="list"

select="com.yayadou.mapper.TeacherMapper.find"/>

</resultMap>

 

<!-- 查询 -->

<select id="get" resultMap="baseResultMap">

select * from student where id = #{id}

</select>

 

 

TeacherMapper.xml文件:

<!-- 查询 -->

<select id="find" resultType="Teacher">

SELECT t.* FROM tea_2_stu AS ts LEFT JOIN student AS s

ON s.id = ts.STU_ID LEFT JOIN teacher AS t

ON t.id = ts.TEA_ID

WHERE s.id = #{id}

</select>

 

 

 

 

 

  结构图

   图1

   图2

  定义实体类

   Student.java

   Teacher.java

  在xxxMapper.xml中配置表之间的多对一关系

   StudentMapper.xml

 

   TeacherMapper.xml

  配置XxxMapper.xml

  执行查询

1.获取SqlSession对象。

 

2.执行查询。

posted on 2018-01-31 23:38  東風★破  阅读(146)  评论(0)    收藏  举报

导航