Mybatis-resultMap的一些用法(映射,关联查询)
通过resultMap来解决冲突
<select id="selll" resultMap="userMap"> select id u_id,name u_name,age u_age from users </select> <resultMap type="com.zhiyou100.xf.bean.Users" id="userMap"> <id column="u_id" property="id"/><!--作为唯一标识--> <result column="u_name" property="name"/> <result column="u_age" property="age"/> </resultMap>
关联查询
一对一、多对一
实体类中将另一个类作为属性association
<!-方式一:嵌套结果:使用嵌套结果映射来处理重复的联合结果的子集 封装联表查询的数据(去除重复的数据) select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=1 -->
<select id="getClass" parameterType="int" resultMap="ClassResultMap">
select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=#{id}
</select>
<resultMap type="_Classes" id="ClassResultMap">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" column="teacher_id" javaType="_Teacher">
<id property="id" column="t_id"/> <result property="name" column="t_name"/> </association>
</resultMap> <!- 方式二:嵌套查询:通过执行另外一个 SQL 映射语句来返回预期的复杂类型 SELECT * FROM class WHERE c_id=1; SELECT*FROMteacherWHEREt_id=1 //1 是上一个查询得到的 teacher_id 的值 --> <select id="getClass2" parameterType="int" resultMap="ClassResultMap2">
select * from class where c_id=#{id}
</select>
<resultMap type="_Classes" id="ClassResultMap2">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" column="teacher_id" javaType="_Teacher" select="getTeacher">
</association>
</resultMap>
<select id="getTeacher" parameterType="int" resultType="_Teacher">
SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id}
</select>
一对多
实体类中将另一个类的list作为属性collection
<select id="selAll" resultMap="AllMap"> select * from teacher,student,class where c_id=class_id and teacher_id=t_id and c_id=#{id} </select> <resultMap type="com.zhiyou100.xf.bean.Classes" id="AllMap"> <id column="c_id" property="cid"/> <result column="c_name" property="cname"/> <association property="teacher" javaType="com.zhiyou100.xf.bean.Teacher"> <id column="t_id" property="tid"/> <result column="t_name" property="tname"/> </association> <collection property="students" ofType="com.zhiyou100.xf.bean.Student"> <id column="s_id" property="sid"/> <result column="s_name" property="sname"/> </collection> </resultMap>