ibatis加载关联关系的两种方法

ibatis有两种加载关联关系的方法:

 1. Nested Select:select另一个加载数据的sql语句id
 <resultMap id="blogResult" type="Blog">
  <association property="author" column="blog_author_id"
   javaType="Author" select="selectAuthor" />
 </resultMap>

 <select id="selectBlog" parameterType="int" resultMap="blogResult">
  SELECT * FROM BLOG WHERE ID = #{id}
 </select>

 <select id="selectAuthor" parameterType="int" resultType="Author">
  SELECT * FROM AUTHOR WHERE ID = #{id}
 </select>
 
 在这里我们有两个select语句,一个去加载blog数据,另一个去加载author数据,在blog定义的resultMap中使用了加载
 author的select语句,对blog中的author属性进行赋值。也就是说,这种简单的一对一关系,执行了两条select语句。
 使用nested select会产生“N+1”问题,非常常见,性能消耗相当大,可以使用懒加载来解决,或者使用下面一种方法。
 
 2.Nested Result:映射关联属性字段的resultMap id值,采用join的方式一次查询得出结果
 <resultMap id="blogResult" type="Blog">
  <id property="blog_id" column="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="blog_id" column="id" />
  <result property="title" column="blog_title" />
  <association property="author" column="blog_author_id"
   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>
 在select语句中使用:
 <select id="selectBlog" parameterType="int" resultMap="blogResult"> select
  B.id as blog_id, B.title as blog_title, B.author_id as blog_author_id,
  A.id as author_id, A.username as author_username, A.password as
  author_password, A.email as author_email, A.bio as author_bio from
  Blog B left outer join Author A on B.author_id = A.id where B.id =
  #{id}
 </select>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值