Mybatis 雜記(三)

Mybatis雜記:
當數據庫涉及到多對多時mybatis的處理辦法:

  • 例如在bean包中定義一下兩個類(Stu類和Course類),學生和課程之間是一對一的關係,一個學生可能對應多個課程,一個課程也可能對應多個學生。
    此時你需要做的就是在兩邊都定義集合,list 和 set都可以!
public class Stu {
    private int id;
    private String name;
    private Set<Course> courses;
    //Getter and Setter
	//toString
	//Constuctor
}
public class Course {
    private long id;
    private String name;
    private Set<Stu> stus;
    //Getter and Setter
	//toString
	//Constuctor
}

有了實體類以後做一些 demo:
1.保存一個學生信息:
在mapper接口中定義:void saveStu(Stu stu);
Mapper.xml文件中:
由於在數據庫(oracle)定義一個序列在維護主鍵,故這樣寫:

<insert id="saveStu" parameterType="stu">
    <selectKey keyProperty="id" resultType="int" order="BEFORE">
        select sc_seq.nextval from dual
    </selectKey>
    insert into s_stu values(#{id},#{name})
</insert>

2.根據課程去查詢所有選課的學生:
在mapper接口中定義:Course findCourseAndStu(long id);
Mapper.xml文件中:

<select id="findCourseAndStu" parameterType="long" resultMap="course2_model">
   select id,name
    from S_COURSE
    where ID = #{id}
</select>

由於Course類中的private Set<Stu> stus;不能從數據中直接查詢到,所以這裏用到resultMap來自定義模板。

<resultMap id="course2_model" type="course">
    <id property="id" column="id"/>
    <result property="name" column="name"/>
    <collection property="stus" column="id" select="findStuByIds"></collection>
</resultMap>

用到collection來維護多對多的這層關係,property屬性值得是你在Course類中定義的那個集合的名字,columnselect表示從哪裏去查詢,這裏再寫一個select如下:

<select id="findStuByIds" parameterType="int" resultType="stu">
    select s.id,s.NAME
    from S_STU s,STU_COU sc
    where s.ID = sc.STU_ID and sc.COU_ID = #{id}
</select>

這就表示根據id號去查詢對應的stu的各個屬性,通過collection最後裝配成一個stu對象。

3.同樣你也可以通過學生去查詢所有的選課,與2中的代碼類似,多對多比起一對多的關係就是由單向轉爲雙向!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章