mybatis映射文件用法小结

mybatis 要点:
一对一:association 一对多:collection

一对一:
association 处理“有一个”类型的关系

嵌套查询(分步查询,可使用懒加载):通过执行另外一个 SQL 映射语句来返回预期的复杂类型。

 	<!-- 通过association进行分步查询 
 		select:设置调用那个接口的那个方法查询该属性
 		column:设置将Employe中那一列的值传入到select属性中的方法中
 	-->
 	<!-- 
 		fetchType:用来设置是否开启延迟加载,该属性的设置将覆盖全局配置文件中的设置值:
 					-lazy:开启延迟加载
 					-eager:关闭延迟加载
 	 -->
 	 <!-- 
 	 	扩展:分步查询传入多个值得情况:
 	 		使用{key1=column1,key2=column2…}的形式来传入多个值
 	 	  -->

嵌套结果:使用嵌套结果映射来处理重复的联合结果的子集。
columnPrefix 当连接多表时,你将不得不使用列别名来避免ResultSet中的重复列名。指定 columnPrefix允许你映射列名到一个外部的结果集中。

	<resultMap id="blogResult" type="Blog">
	  <id property="id" column="blog_id" />
	  <result property="title" column="blog_title"/>
	  <association property="author" column="blog_author_id" javaType="Author" resultMap="authorResult"/>
	</resultMap>
	不重用:
	<resultMap id="authorResult" type="Author">
	  <id property="id" column="author_id"/>
	  <result property="username" column="author_username"/>
	  <result property="password" column="author_password"/>
	  <result property="email" column="author_email"/>
	  <result property="bio" column="author_bio"/>
	</resultMap>
	重用:
	<resultMap id="blogResult" type="Blog">
	  <id property="id" column="blog_id" />
	  <result property="title" column="blog_title"/>
	  <association property="author" javaType="Author">
	    <id property="id" column="author_id"/>
	    <result property="username" column="author_username"/>
	    <result property="password" column="author_password"/>
	    <result property="email" column="author_email"/>
	    <result property="bio" column="author_bio"/>
	  </association>
	</resultMap>

一对多:collection

<select id="selectBlog" resultMap="blogResult">
  select
  B.id as blog_id,
  B.title as blog_title,
  B.author_id as blog_author_id,
  P.id as post_id,
  P.subject as post_subject,
  P.body as post_body,
  from Blog B
  left outer join Post P on B.id = P.blog_id
  where B.id = #{id}
</select>

<resultMap id="blogResult" type="Blog">
  <id property="id" column="blog_id" />
  <result property="title" column="blog_title"/>
  <collection property="posts" ofType="Post">
    <id property="id" column="post_id"/>
    <result property="subject" column="post_subject"/>
    <result property="body" column="post_body"/>
  </collection>
</resultMap>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值