项目_06_MyBatils多表查询

#MyBatis多表查询(映射)

查询多个数据表,返回结果如何映射成实体对象。

##多条关联记录的封装

例如:一个Subject课程,对应多个Stage阶段  
需求:查询课程信息,并且获取相关的多个阶段信息  
做法:

- 首先在Subject实体类中追加一个List集合的stages

        private List<Stage> stages;

- 然后在SQL定义文件,编写了一个多表关联查询SQL语句

         <select id="findAllAssociation" resultMap="subjectMap">
             select s1.id id,s1.name name,s2.id sid,s2.name sname,subject_id 
             from x_subject s1 join x_stage s2 on(s1.id=s2.subject_id)
         </select>

- 最后将resultType属性改为resultMap,指定stages属性装载

         <resultMap id="subjectMap" type="com.xdl.entity.Subject">
             <id property="id" column="id"/>
             <result property="name" column="name"/>
             <!-- list集合 -->
             <collection property="stages" javaType="java.util.List" 
                 ofType="com.xdl.entity.Stage">
                 <id property="id" column="sid"/>
                 <result property="name" column="sname"/>
                 <result property="subject_id" column="subject_id"/>
             </collection>
         </resultMap>




##单条关联记录的封装

需求:查询某个阶段信息,及其相关课程信息

做法:

- 首先在Stage实体类中追加一个subject属性

        private Subject subject;

- 然后在StageMapper.xml中定义多表关联的SQL语句

        <select id="findAll" resultMap="stageMap">
            select s1.id sid,s1.name sname,s1.subject_id,s2.id,s2.name 
            from x_stage s1 join x_subject s2 on(s1.subject_id=s2.id)
        </select>

- 最后利用resultMap替代resultType,指定subject属性装载

         <resultMap id="stageMap" type="com.xdl.entity.Stage">
             <id property="id" column="sid"/>
             <result property="name" column="sname"/>
             <result property="subject_id" column="subject_id"/>
             <!-- 关联映射subject -->
             <association property="subject" javaType="com.xdl.entity.Subject">
                 <id property="id" column="id"/>
                 <result property="name" column="name"/>
             </association>
         </resultMap>

欢迎转载:海阔天空 » 项目_06_MyBatils多表查询

评论 沙了个发

换个身份

取消评论