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中的代码类似,多对多比起一对多的关系就是由单向转为双向!

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