Mybatis-resultMap的一些用法(映射,關聯查詢)


通過resultMap來解決沖突

<select id="selll" resultMap="userMap">       
 select id u_id,name u_name,age u_age from users
    </select>
    <resultMap type="com.zhiyou100.xf.bean.Users" id="userMap">
        <id column="u_id" property="id"/><!--作為唯一標識-->
        <result column="u_name" property="name"/>
        <result column="u_age" property="age"/>
    </resultMap>

關聯查詢

一對一、多對一

實體類中將另一個類作為屬性association

<!-方式一:嵌套結果:使用嵌套結果映射來處理重復的聯合結果的子集 封裝聯表查詢的數據(去除重復的數據) select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=1 -->

<select id="getClass" parameterType="int" resultMap="ClassResultMap">
select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=#{id}
</select>
<resultMap type="_Classes" id="ClassResultMap">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" column="teacher_id" javaType="_Teacher">
<id property="id" column="t_id"/> <result property="name" column="t_name"/> </association>
</resultMap> <!- 方式二:嵌套查詢:通過執行另外一個 SQL 映射語句來返回預期的復雜類型 SELECT * FROM class WHERE c_id=1; SELECT*FROMteacherWHEREt_id=1 //1 是上一個查詢得到的 teacher_id 的值 --> <select id="getClass2" parameterType="int" resultMap="ClassResultMap2">
select * from class where c_id=#{id}
</select>
<resultMap type="_Classes" id="ClassResultMap2">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" column="teacher_id" javaType="_Teacher" select="getTeacher">
</association>
</resultMap>
<select id="getTeacher" parameterType="int" resultType="_Teacher">
SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id}
</select>

一對多

實體類中將另一個類的list作為屬性collection

<select id="selAll" resultMap="AllMap">
        select * from teacher,student,class where c_id=class_id and teacher_id=t_id and c_id=#{id}
    </select>
    <resultMap type="com.zhiyou100.xf.bean.Classes" id="AllMap">
        <id column="c_id" property="cid"/>
        <result column="c_name" property="cname"/>
        <association property="teacher" javaType="com.zhiyou100.xf.bean.Teacher">
            <id column="t_id" property="tid"/>
            <result column="t_name" property="tname"/>
        </association>
        <collection property="students" ofType="com.zhiyou100.xf.bean.Student">
            <id column="s_id" property="sid"/>
            <result column="s_name" property="sname"/>
        </collection>
    </resultMap>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM