多对一和一对多
多对一查询的实现方式
1.子查询 [SQL简单,映射复杂]
Student 类: int id ;String name; Teacher teacher
Teacher类:int id ; String name;
<select id="getStudent" resultMap="Student_Teacher">
select * from mybatis.student
select>
<resultMap id="Student_Teacher" type="Student">
<association property="teacher" column="tid"
javaType="Teacher" select="getTeacher"/>
resultMap>
<select id="getTeacher" resultType="Teacher">
select * from mybatis.teacher where id=#{id_sb}
select>
在student表内利用getStudent获取全部的学生 返回类型为Student , 但是因为学生的属性是 ID name 和 teacher对象, 所以返回类型需要使用resultMap加以"扩展", 在里面进行新的关系映射( teacher对象映射为tid字段),并且指定javaType ,然后根据映射的字段,在teacher表内查询(结果赋给student对象的teacher属性)
2.连表查询(推荐) [SQL复杂,映射简单]
直接通过sql语句查询出来,然后映射到属性
<select id="getStudent" resultMap="Student_Teacher"> SELECT s.id sid,s.name sname,t.name tname ,t.id tid from mybatis.student s,mybatis.teacher t WHERE s.tid=t.id select> <resultMap id="Student_Teacher" type="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" javaType="Teacher"> <result property="name" column="tname"/> <result property="id" column="tid"/> association> resultMap>
通过起别名和连表查询在数据库中得到新表α
仍然通过resultMap"扩展", 经过与新表α属性名-字段的关系映射 ,直接获得结果
属性名:JAVA类中的属性名
字段:数据库中的字段
一对多实现
<select id="get_Teacher_students" resultMap="Student_Teacher"> SELECT s.id sid,s.name sname,t.name tname ,t.id tid from mybatis.student s,mybatis.teacher t WHERE s.tid=t.id and t.id=#{id} select> <resultMap id="Student_Teacher" type="Teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <collection property="student" ofType="Student" > <result property="name" column="sname"/> <result property="id" column="sid"/> collection> resultMap>
数据库
teacher:id name
studnet: id name tid (tid=id)
使用嵌套查询实现:
javaType="ArrayList" :指定实体类中属性的类型 (可省略)
ofType="Student" :指定映射到list或者集合中的类型,泛型中的约束类型()
<select id="get_Teacher_students02" resultMap="Student_Teacher02"> select * from mybatis.teacher where id=#{tid} select> <resultMap id="Student_Teacher02" type="Teacher"> <collection property="student" javaType="ArrayList" ofType="Student" select="getStudentByteacher" column="id"/> resultMap> <select id="getStudentByteacher" resultType="Student"> select * from mybatis.student where tid=#{tid_sb} select>
先select查询到指定ID的老师, 对返回结果进行拓展, 里面的student集合α(通过另外一个select 查询得到)
select :利用colum传递查询的条件id(老师的id) 对学生表的tid字段进行查询,得到符合条件的student集合α
mysql引擎
InnoDB的底层原理
索引
索引优化