Mybatis-resultMap

实体关系:
一对一:班级==>班长
一对多:班级==>学生
多对多:课程==>学生

resultMap 元素是 MyBatis 中最重要最强大的元素。
解决多表,也就是链表查询的问题

ResultMap 的设计思想是,对简单的语句根本不需要配置显示的结果映射,对于复杂一点的语句,只需要描述语句之间的关系就行了。
Tips:Mybatis封装实体类,使用的构造器是无参构造

一、解决属性名和字段名不一致的问题(resultMap)

数据库中的字段

新建一个项目,拷贝之前的,测试实体类字段不一致的情况

public class User {
    private int id;
    private String name;
    private String password;
}

测试出现问题!

select * from test where id = #{id}
<!--类型处理器-->
<!--SQL完整语句应该是:select id,name,pwd from test where id = #{id}-->

解决方法:

  • 方法一:sql语句起别名
select id,name,pwd as password from test where id = #{id}
  • 方法二:resultMap(结果集映射)
    其实这些简单的sql根本不需要使用resultMap。
<!--结果集映射-->
<resultMap id="UserMap" type="User">
	<!--column数据库中的字段名,property实体类中的属性名-->
	<result column="id" property="uid" />
	<result column="name" property="uname" />
	<result column="pwd" property="upassword" />
</resultMap>
<!--resultMap="随便起名字"上面的UserMap-->
<select id="getUserById" parameterType="int" resultMap="UserMap">
	select * from test where id = #{id}
	<!--类型处理器-->
	<!--SQL完整语句应该是:select id,name,pwd from test where id = #{id}-->
</select>

如果世界这么简单就好了

二、解决属性是对象/集合的封装问题

多对一:学生—>班级
pojo

public class St {
    private Integer sid;
    private String sname;
    private Integer mid;
    private MyClass myClass;
	/*get、set*/
}

mapper.xml

<select id="findStAndMyClassBySid" parameterType="Integer" resultMap="getSt">
	select * from st s,myclass m where s.mid=m.mid and s.sid=#{sid}
</select>

<resultMap type="St" id="getSt">
	<id property="sid" column="sid"/>
	<result column="sname" property="sname"/>
	<result property="mid" column="mid"/>
	<association property="myClass" javaType="MyClass">
		<id property="mid" column="mid"/>
		<result property="myname" column="myname"/>
	</association>
</resultMap>

一对多:班级——>学生
pojo

public class MyClass {
    private Integer mid;
    private String myname;
    private List<St> sts;
}

mapper.xml

<select id="findStAndMyClassByMid" parameterType="int" resultMap="getMyClass">
    select * from st s,myclass m where s.mid=m.mid and s.mid=#{mid}
</select>

<resultMap type="MyClass" id="getMyClass">
	<id property="mid" column="mid"/>
	<result property="myname" column="myname"/>
	<collection property="sts" javaType="List" ofType="St">
	   <id property="sid" column="sid"/>
	   <result property="sname" column="sname"/>
	   <result property="mid" column="mid"/>
	</collection>
</resultMap>
posted @ 2021-09-26 13:23  生生灯火半杯月  阅读(77)  评论(0)    收藏  举报