在mybatis中如何实现一对一、一对多?

在mybatis中有两种写法:

以Student类和Banji类为列

public class Student {
	// 属性
	private int sid;
	private String sname;
	private Date birthday;
	private String ssex;
	private int classid;
    
    //一个学生对应一个班级 (一对一的关系)
	private Banji bj;
}
public class Banji {

	//属性
	private int classid;
	private String classname;
	
	//一个班级有多个学生(一对多的关系)
	private List<Student> stuList;
}

一、xml文件写法

1.一对一(用association标签)

<!-- 多表必须全部写字段和属性的映射关系 -->
-<resultMap id="stu_class_Map" type="Student">

    <result property="sid" column="sid"/>

    <result property="sname" column="sname"/>

    <result property="birthday" column="birthday"/>

    <result property="ssex" column="ssex"/>

    <result property="classid" column="classid"/>

    <!-- association 一对一  其中property写Banji类型的属性名-->
    <association property="bj">

        <result property="classid" column="classid"/>

        <result property="classname" column="classname"/>

    </association>

</resultMap>

<select id="findAllStudent" resultMap="stu_class_Map">
      select * from studentinner join class on student.classid = class.classid 
</select>

2.一对多(使用collection标签)

-<resultMap id="bj_stu_Map" type="Banji">

    <result property="classid" column="classid"/>

    <result property="classname" column="classname"/>

    <!-- 一对多 collectionproperty 集合的属性名 ofType 集合中每个元素的类型 -->

    <collection property="stuList" ofType="Student">

        <result property="sid" column="sid"/>

        <result property="sname" column="sname"/>

    </collection>

</resultMap>

<select id="findAllBanji" resultMap="bj_stu_Map">
    select * from classleft join student on class.classid = student.classidorder by             
    class.classid 
</select>

二、注解写法

1.一对一(one)

//一对一
	@Results({
			@Result(column="classid",property="classid"),
			
			@Result(column="classid",property="bj",
			
					one=@One(select="com.ape.mapper.BanjiMapper.findBanjiByclassid"))
                    //select中写的是"包名.接口名.方法名"
	})
	@Select("select * from student")
	public List<Student>findStuAndBanji();

    //select中以BanjiMapper接口为列
    @Select("select * from banji where classid=#{v}")
	public Banji findBanjiByclassid(int classid);

2.一对多(many)

//多对多
	@Results({
		@Result(column="classid",property="classid"),
		@Result(column="classid",property="stuList",
				many = @Many(select = "com.ape.mapper.StudentMapper.findStudentByClassid"))
                //select中写的是"包名.接口名.方法名"
	})
	@Select("select * from banji")
	public List<Banji> findAllBanjiandStudent(); 
    
    //select中以StudentMapper接口为列
    @Select("select * from student where classid=#{v}")
	public List<Student>findStudentByClassid(int cid);
经验分享 程序员 微信小程序 职场和发展