- [ MyBatis ]

八,Mybatis的OneToMany对象关联查询

2021-01-10  本文已影响0人  好多可乐
在这里插入图片描述
关系:

1,班级和学生:班级1--n学生

1个班级--》n(多)个学生,,1个学生--》(同一时间)1个班级

这样,多对一的学生表需要持有班级的 外键

2,学生和学籍档案

1个学生--》1份档案,,1份档案--》1个学生

这样,1对1的关系通常通过主键进行关联(1号学生-对应-》1号档案)

3,学生和课程的关系

1个学生--》n课程,,1个课程--》你个学生

这样多对多的关系--》设计数据表时需要出现出一个 中间表 ,中间表持有课程和学生的编号,学生表与中间表关联,课程表与中间表关联,这样三张表就构建起一个多对多关系。

一、一对多的关系查询

  1. 各个表格需要创建对应的实体类。并使用集合的形式体现一对多关系(在Good中创建一个List属性,集合元素为"多"方的实体对象)
public class GoodsDetail {
    private int gdId;
    private int goodsId;
    private String gdPicUrl;
    private String gdOrder;

    public int getGdId() {
        return gdId;
    }

    public void setGdId(int gdId) {
        this.gdId = gdId;
    }

    public int getGoodsId() {
        return goodsId;
    }

    public void setGoodsId(int goodsId) {
        this.goodsId = goodsId;
    }

    public String getGdPicUrl() {
        return gdPicUrl;
    }

    public void setGdPicUrl(String gdPicUrl) {
        this.gdPicUrl = gdPicUrl;
    }

    public String getGdOrder() {
        return gdOrder;
    }

    public void setGdOrder(String gdOrder) {
        this.gdOrder = gdOrder;
    }
}

// 创建实体类
public class Goods {
    private int goodsId;
    private String title;
    private String subTitle;
    private float originalCost;
    private float currentPrice;
    private float discount;
    private int isFreeDelivery;
    private int categoryId;
    private List<GoodsDetail> goodsDetails;

    public List<GoodsDetail> getGoodsDetails() {
        return goodsDetails;
    }

    public void setGoodsDetails(List<GoodsDetail> goodsDetails) {
        this.goodsDetails = goodsDetails;
    }

    public int getGoodsId() {
        return goodsId;
    }

    public void setGoodsId(int goodsId) {
        this.goodsId = goodsId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSubTitle() {
        return subTitle;
    }

    public void setSubTitle(String subTitle) {
        this.subTitle = subTitle;
    }

    public float getOriginalCost() {
        return originalCost;
    }

    public void setOriginalCost(float originalCost) {
        this.originalCost = originalCost;
    }

    public float getCurrentPrice() {
        return currentPrice;
    }

    public void setCurrentPrice(float currentPrice) {
        this.currentPrice = currentPrice;
    }

    public float getDiscount() {
        return discount;
    }

    public void setDiscount(float discount) {
        this.discount = discount;
    }

    public int getIsFreeDelivery() {
        return isFreeDelivery;
    }

    public void setIsFreeDelivery(int isFreeDelivery) {
        this.isFreeDelivery = isFreeDelivery;
    }

    public int getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(int categoryId) {
        this.categoryId = categoryId;
    }
}

  1. 创建数据表对象对应的映射文件:并在映射文件中对应好表格之间的对应关系。
<?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="goodsDeatil">
    <select id="selectById" parameterType="int" resultType="com.imooc.mybatis.entity.GoodsDetail">
        select * from t_goods_detail where goods_id= #{value}
    </select>
</mapper>

(注意:映射文件配置好后,需要在Mybatis-config.xml的mappers标签中注册才能生效)

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--设置成支持驼峰命名-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!--默认环境配置-->
    <environments default="dev">
        <!--支持配置多套环境-->
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <!--采用连接池方式管理数据库连接-->
            <dataSource type="POOLED">
                <!--配置数据库连接信息-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql://localhost:3306/babytun?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false&amp;serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--声明goods.xml类,让mybatis认识这个文件-->
    <mappers>
        <mapper resource="mappers/goods.xml"/>
        <mapper resource="mappers/goods_detail.xml"/>
    </mappers>
</configuration>
  1. 使用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="goods">
    <!--resultMap可用于说明一对多或多对一的映射逻辑
    id是resultMap属性的引用标志
    type指向one的实体(goods)-->
    <resultMap id="rmGoods1" type="com.imooc.mybatis.entity.Goods">
        <!--映射goods对象的主键到goods_id字段-->
        <id column="goods_id" property="goodsId"></id>
        <!--collection的含义是在 select * from  t_goods_detail limit 0 1得到结果后,对所有goods对象遍历得到goods_id的字段值,并带入到goodsDetail命名空间的selectById的sql执行查询,
        将得到的商品详情集合赋值给goodsDetails list对象-->
        <collection property="goodsDetails" select="goodsDeatil.selectById" column="goods_id"></collection>
    </resultMap>
    <select id="selectOneToMany" resultMap="rmGoods1">
        select * from  t_goods limit 0,1
    </select>
</mapper>

测试

   @Test
    public void testOneToMany() {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.openSession();
            List<Goods> goods = sqlSession.selectList("goods.selectOneToMany");
            for (Goods good : goods) {
                System.out.println(good.getTitle() + "--" + good.getGoodsDetails().size());
            }
        } catch (Exception e) {
            throw e;
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
    }
上一篇下一篇

猜你喜欢

热点阅读