假如通过MyBatis里dao.xml传递返回值时,返回值实体类型关系映射是
实体—-表关系 映射:
ORM映射(多张表)
1-n
//班级信息管理系统:(班级信息,学生信息)
数据库设计: FK
–班级表
create table t_class(
c_id integer primary key,
c_name varchar2(100)
);
–学生表
create table t_student(
s_id integer primary key,
s_name varchar2(100),
s_age number(4),
c_id integer references t_class(c_id)–外键指向班级表的c_id
);
此时,应采用resultMap以及表连接
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="day3pm.ClazzDAO">
<resultMap type="day3pm.Clazz" id="clazz">
<id property="clazzId" column="c_id"/>
<result property="className" column="c_name"/>
<!-- clazz has many stu -->
<collection property="students" javaType="day3pm.Student">
<id property="stuId" column="s_id"/>
<result property="stuName" column="s_name"/>
<result property="stuAge" column="s_age"/>
</collection>
</resultMap>
<select id="queryClazz" parameterType="java.lang.Integer"
resultMap="clazz">
select c.c_id,c.c_name,s.s_id,s.s_name,s.s_age
from
t_class c
left join t_student s on c.c_id = s.c_id where c.c_id = #{clazzId}
</select>
</mapper>
其中外层id为主体的主属性,result为主体的一般属性,collection为主体的关系属性,collection内部为另一个实体的主属性和一般属性
但如果是多对多,则必须在数据库表创立时再加一个表,即两个实体三个表,第三个作为关系表存在
数据库设计:
--测试数据
学生信息
学号 名字 年龄 科目id(外键)--不可行
100 金龙 24 100001×
101 刘璐璐 21
科目信息
科目编号 科目名称
100001 CoreJava
100002 Oracle
100003 JDBC
选课表:--
学号 科目id
100 100001
100 100002
101 100001
100 100001 ×
create table t_stu_course(
stu_id integer references t_student(stu_id),
course_id integer references t_course(course_id),
primary key(stu_id,course_id)
);
*单独创建一个关系表。将外键创建在关系表中
但在建立实体时,与一对多没有太大区别,还是以一个为主体,另一个作为主体的关系属性,只是把xml里的sql语句修改一下即可。