前言:日常开发中,我们经常会使用到resultMap的封装。为此整理一份封装手册。
通常讲的一对一、一对多。我们可以类比为A对B、X对Y。此时我们的主视角都站在A、X方。
- 一对一关系
- 例如: 一个儿子对应一个父亲
-
<!-- 儿子 --> <resultMap id="getSon" type="com.entity.Son"> <id column="ID" property="id" jdbcType="INTEGER" /> <result column="NAME" property="name" jdbcType="VARCHAR" /> <!-- 父亲--> <association property="father" javaType="com.entity.Father"> <id column="F_ID" property="id" jdbcType="INTEGER" /> <result column="F_NAME" property="name" jdbcType="VARCHAR" /> </association> </resultMap>
- 一对多关系
- 例如:一个父亲对应多个儿子
-
<!-- 父亲 --> <resultMap id="getFather" type="com.entity.Father"> <id column="ID" property="id" jdbcType="INTEGER" /> <result column="NAME" property="name" jdbcType="VARCHAR" /> <!-- 儿子--> <collection property="sonList" ofType="com.entity.Son"> <id column="S_ID" property="id" jdbcType="INTEGER" /> <result column="S_NAME" property="name" jdbcType="VARCHAR" /> <collection > </resultMap>
- 多对多关系
- 例: 多个社团对应多个学生 ( 一个社团可以有多个学生,一个学生也可以有多个社团 )
-
<!-- 学生 --> <resultMap id="getStudent" type="com.entity.Student"> <id column="ID" property="id" jdbcType="INTEGER" /> <result column="NAME" property="name" jdbcType="VARCHAR" /> <!-- 社团--> <collection property="clubList" ofType="com.entity.Club"> <id column="C_ID" property="id" jdbcType="INTEGER" /> <result column="C_NAME" property="name" jdbcType="VARCHAR" /> <collection > </resultMap>