MyBatis中 collection 的两种使用方法,及效率比较

方案一

     <resultMap type="Student" id="StudentMap">
          <id column="id" property="id" />
          <result column="name" property="name" />
          <result column="job" property="job" />
          <collection property="scores" ofType="Score" column="id"  select="queryScoresBySID" ></collection>
     </resultMap>
     <resultMap type="Score" id="ScoreMap">
          <id column="id" property="id" />
          <result column="num" property="num" />
          <association property="subject" javaType="Subject" column="subject" select="querySubjectBySubId"></association>
     </resultMap>
     <select id="queryStudents" resultMap="StudentMap" >
          SELECT id,name,job FROM t_student
     </select>
     <select id="queryScoresBySID" resultMap="ScoreMap">
          SELECT id,num,subject FROM t_score WHERE sid = #{sid}
     </select>
     <select id="querySubjectBySubId" resultType="Subject" >
          SELECT id,name FROM t_subject where id = #{id}
     </select>

方案二

     <resultMap type="Student" id="StudentMap2">
          <id column="id" property="id" />
          <result column="name" property="name" />
          <result column="job" property="job" />
          <collection property="scores" javaType="java.util.ArrayList" ofType="Score">
              <id column="id" property="id" />
              <result column="num" property="num" />
              <association property="subject" javaType="Subject">
                   <id column="id" property="id" />
                   <result column="name" property="name" />
              </association>
          </collection>
     </resultMap>
     <select id="queryStudents2" resultMap="StudentMap2" >
          SELECT stu.id,stu.name name,stu.job,sco.id id,sco.num num,sub.id id,sub.name name
          FROM t_student stu LEFT JOIN t_score sco ON stu.id = sco.sid LEFT JOIN t_subject sub ON sco.subject = sub.id
     </select>

比较

方案一:需要执行至少三次sql语句,开启三次事务才能完成本次请求。
方案二:需要执行一次sql语句,开启一次事务就能完成本次请求

方案二比方案一的效率要高,但是在使用的时候,方案一的代码可重用性要高

如果想要追求代码重用性可以选择方案一
如果比较在乎运行的性能可以选择方案二

转自 https://blog.csdn.net/sinat_32869075/article/details/52872841#commentBox



升级版 https://blog.csdn.net/u010018421/article/details/77620145


猜你喜欢

转载自blog.csdn.net/hlz5857475/article/details/80896772