在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);
	

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值