mybatis 关联查询
- (1)项目不可能只有一个表,一般是多表
- (2)多表关系为,一对一,一对多,多对多
- (3)查询的数据来自多个表,要使用多表查询
笛卡尔集,显示内连接inner join
,左外连接left outer join
,右外连接right outer join
,子查询select嵌套select - (4)查询的结果要封装成
javaBean
对象 ,在Mybatis中重点掌握resultType与resultMap
一对一(association)
一对一查询有两种方式
- 第一种:在配置文件中,标签的属性选择resultType,但是这种方式的话,要求新建一个与查询结果一样的JavaBean类
- 第二种:在配置文件中,标签的属性选择resultMap,使用这种方式不需要新建一个与查询结果一样的JavaBean类,
只需要向下图中,再类中添加一个属性就行了
产品表(Products)与分类表(Category)
一个产品属于一种分类,一种分类有多个产品
ProductsDao.xml
<?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">
<!-- map的约束文件-->
<!-- namespace 命名空间 防止id冲突找不到正确的id-->
<!-- id Mybatis是将sql语句写在xml文件中,以后session根据namespace.id 合在一起获取sql-->
<!-- 在jdbc中,sql语句使用?作占位符,但在mybatis #{id}-->
<mapper namespace="com.lxy.dao.ProductsDao">
<resultMap id="findAllMap" type="com.lxy.bean.Products">
<id column="pid" property="id"/>
<result column="pname" property="name"/>
<result column="price" property="price"/>
<result column="flag" property="flag"/>
<association property="category" javaType="com.lxy.bean.Category">
<id column="cid" property="id"/>
<result column="cname" property="name"/>
</association>
</resultMap>
<select id="findAll" resultMap="findAllMap">
SELECT p.pid,p.pname,p.price,p.flag,c.cid,c.cname
from products p,category c
where p.category_id = c.cid
</select>
</mapper>
一对多(collection)
ProductsDao.xml
<resultMap id="findCategoryAllMap" type="com.lxy.bean.Category">
<id column="cid" property="id"/>
<result column="cname" property="name"/>
<collection property="list" ofType="com.lxy.bean.Products">
<id column="pid" property="id"/>
<result column="pname" property="name"/>
<result column="price" property="price"/>
<result column="flag" property="flag"/>
</collection>
</resultMap>
<select id="findCategoryAll" resultMap="findCategoryAllMap">
SELECT c.cid,c.cname,p.pid,p.pname,p.price,p.flag
from category c
LEFT JOIN products p
on c.cid = p.category_id
</select>
配置映射文件
-
写完映射文件后一定要记得去mybatis核心文件标签中去配置一下,不然在运行的时候,就会报错。