Mybatis基础教程(三)

来源:互联网 发布:儿童围棋软件 编辑:程序博客网 时间:2024/05/22 02:55

ORM(object relational mapping)关系映射

前面讲的关系映射都是单表的操作,今天实现多表的操作

创建两张表学生(n)表和班级(1)表 1对n

Clazz班级表有c_id(主键),c_name字段
Student学生表有s_age,s_name,s_id(主键),c_id(外键)字段

如果我们主要需要的是学生信息
对应的实体类
学生类:
public class Student{private String sName;private Integer sAge;private Integer sId;private Clazz clazz;//构造方法和get set方法省略}

班级类:
public class Clazz{private Integer cId;private String cName;//构造方法和get set方法省略}


映射(mapper)文件

<mapper namespace=" "><!--告诉mybatis查询结果集合和尸体的映射关系--><resultMap id="stu" type="包名.Student(映射的实体的全类名)"><id property="实体的属性名" column="对应的数据库列名"/><result property="实体的属性名" column="对应的数据库列名"/>......<assocation property="clazz" javaType="包名.Clazz"><id property="实体的属性名" column="对应的数据库列名"/><result property="实体的属性名" column="对应的数据库列名"/>......</assocation></resultMap><select id="实现的方法名" parameterType="java.lang.Integer" resultMap="stu(对应上面的id)" >sql语句</select></mapper>




如果我们主要需要的是班级信息
对应的实体类
学生类:
public class Student{private String sName;private Integer sAge;private Integer sId;//构造方法和get set方法省略}

班级类:
public class Clazz{private Integer cId;private String cName;private List<Student> students=new ArrayList<>();//必须实例化        //构造方法和get set方法省略}

映射文件主要就是把resultMap里的assocation换成了collection标签其他的差不多一样
上面resultMap的id表示主属性的映射,result表示一般属性的映射
原创粉丝点击