association关键字:
关联表数据在这个mxl中写
resultmap:
表联查映射
多对一关系
public class Student {
private Integer sid;
private String sname;
private String address;
private Integer cid;
private Cls cls;
//这的表的关系是多对一,因为一个Student对应的是一个Cls对象
}
<mapper namespace="com.dao.StudentMap">
<!--这里要声明接口,如果不说明路径就无法找到实现接口-->
<resultMap id="StuAndCls" type="com.dao.Student">
<!--映射文件名,返回的类型-->
<result column="sid" property="sid"/>
<!--数据库的列,对应的对象属性-->
<result column="sname" property="sname"/>
<result column="address" property="address"/>
<result column="cid" property="cid"/>
<association property="cls" javaType="com.dao.Cls">
<!--关联表的数据,将com.dao.Cls对象封装道Student中的cls属性中-->
<result column="cid" property="cid"/>
<!--说明要嵌套查询的对象所对应的数据-->
<result column="cname" property="cname"/>
</association>
</resultMap>
<select id="selseAll" resultMap="StuAndCls">
-- id对应着的是接口的实现方法
-- resultMap查询后返回将数据封装道StuAndCls映射文件中的属性中,再将对象返回出来
SELECT s.*,c.cname FROM student s INNER JOIN cls c ON s.cid=c.cid
</select>
</mapper>
一对多关联关系
collection:集合查询
public class Cls {
private Integer cid;
private String cname;
private List<Student> studentList;
//这里之所以要用集合是因为我在联查Cls是希望他将关联的Student对象全部拿出来
//也是因为一个cls表中有多个student对象
}
<mapper namespace="com.dao.Clsmap">
<!--对应的实现接口路径-->
<resultMap id="ClsAndStu" type="com.dao.Cls">
<id column="cid" property="cid"/>
<result column="cname" property="cname"/>
<collection property="studentList" ofType="com.dao.Student">
<!--collection:集合对象-->
<!--将com.dao.Student类型封装到cls对象中的studentList属性当中-->
<!--集合所返回的类型要中ofType声明-->
<!--下面就是student表所对应的属性-->
<id column="sid" property="sid"/>
<result column="sid" property="sid"/>
<result column="sname" property="sname"/>
<result column="address" property="address"/>
<result column="cid" property="cid"/>
</collection>
</resultMap>
<select id="selectClsStu" resultMap="ClsAndStu">
SELECT c.*,s.sid,s.address,s.sname FROM cls c
INNER JOIN student s ON c.cid=s.cid
</select>
</mapper>
懒加载:
运用的是动态代理模式:
1.首先继承你需要的类
2.在内存中生成继承对象
3.重写继承对象中的封装方法
在你的封装方法中询问是否查询过,没查询在查询将对象返回出来
优点是你要用我才给你差不用我就不查
缺点查询效率没有联查效率高
public List<Student> selseAll1(int id);
<select id="selseAll1" resultType="com.dao.Student">
select *from student where cid=#{param1}
-- 查询student按住键查询
</select>
</select>
<resultMap id="ClsAndStu1" type="com.dao.Cls">
<id column="cid" property="cid"/>
<result column="cname" property="cname"/>
<collection property="studentList" column="cid" fetchType="lazy" select="com.dao.StudentMap.selseAll1">
<!--collection因为有多个对象所以用到集合-->
<!--因为是实现接口是按主键查询所以需要传入你要查询的id-->
<!--将cls对象所对应的cid传给com.dao.StudentMap.selseAll1实现类所对应的方法-->
<!--fetchType声明时懒查询-->
<!--select,调用StudentMap.selseAll1接口中的方法,将查询结果值交给cls对象中的studentList集合属性-->
</collection>
</resultMap>
<select id="selectClsStu2" resultMap="ClsAndStu1">
-- 返回类型是映射文件ClsAndStu1中的属性
SELECT c.*,s.sid,s.address,s.sname FROM cls c
INNER JOIN student s ON c.cid=s.cid
</select>