1.ORM:对象与表作映射
2.表与表之间关系(主外键):一对一、一对多、多对一、多对多
3.类与类之间利用属性实现关系:一对一、一对多、多对一、多对多
class Person{
Car car=new Car();//一对一
List<Car> list=new ArrayList<Car>(); //一对多
}
class Car{
Person p=new Person(); //多对一
List<Person> ps=new ArrayList<Person>();
}
Mybatis关联映射查询:
一、功能:查询年级及年级下的学生
实现从属查询(一对多查询)
1.修改实体实现关联关系:
public class Grade {
private Integer gid;
private String gname;
//实现一对多关系
private List<Students> students;
}
public class Students{ 学生类的一系列私有属性....}
2.实现持久化操作:
2.1定义方法
List<Grade> getAllGrade();
2.2持久化操作:利用resultMap返回关联映射结果
<select id="getAllGrade" resultMap="gradeStudentResult">
SELECT * FROM grade left JOIN
students ON grade.`gid`=students.`gid`
</select>
<!-- 查询所有的年级及对应的学生 从主键关联到外键 -->
<resultMap id="gradeStudentResult" type="com.grade.entity.Grade">
<id column="gid" jdbcType="INTEGER" property="gid" />
<result column="gname" jdbcType="VARCHAR" property="gname" />
<!-- 一对多的配置
property 表示集合属性
javaType 表示集合类型
ofType 集合关联的泛型
notNullColumn 表示为空列不进行映射(不产生对象)
resultMap 表示指结果映射类型
-->
<collection property="students" javaType="java.util.List" ofType="com.grade.entity.Students" notNullColumn="xh">
<id column="xh" jdbcType="INTEGER" property="xh" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
<result column="sex" jdbcType="VARCHAR" property="sex" />
</collection>
</resultMap>
二、功能:查询学生及关联的年级.(多对一的查询)
(推荐)第一方法:组合实体类
1.组合实体类
public class Students {
//添加年级名称属性(组合属性)
private String gname;
常规的学生一系列属性...
}
2.定义持久化操作
方法:
List<Students> getAllStudent();
持久化操作:
<select id="getAllStudent" resultType="Students">
select students.*,gname from students left join grade
on students.gid=grade.gid
</select>
第二方法:利用关联映射
2.1建立实体之间的关联关系
public class Students {
//定义多对一关联
private Grade grade;
}
class Grade{ 一系列的年级相关属性...}
2.2实现持久化操作及关联的映射
方法:
List<Students> getAllStudent();
操作:
<!-- 查询所有学生及年级 -->
<resultMap id="studentGradeResult" type="com.grade.entity.Students">
<id column="xh" jdbcType="INTEGER" property="xh" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
<result column="sex" jdbcType="VARCHAR" property="sex" />
<result column="birthday" jdbcType="DATE" property="birthday" />
<result column="address" jdbcType="VARCHAR" property="address" />
<result column="tel" jdbcType="CHAR" property="tel" />
<result column="state" jdbcType="TINYINT" property="state" />
<result column="gid" jdbcType="INTEGER" property="gid" />
<!-- 配置多对一关联 -->
<association property="grade" javaType="com.grade.entity.Grade">
<id column="gid" property="gid"></id>
<result column="gname" property="gname"/>
</association>
</resultMap>
<select id="getAllStudent" resultMap="studentGradeResult">
select students.*,gname from students left join grade
on students.gid=grade.gid
</select>