Mybatis怎么进行多表查询

时间:2024-5-25    作者:老大夫    分类: SSM


对应关系类

对一: 将对应的实体类创建一个对象封装在类中用来存储对象的信息
对多: 创建一个对方类型的集合,List< Object>

对一映射xml怎么写

  • 还是正常写sql语句
  • 使用ResultMap来映射属性和数据库列名的关系
  • 类中还包含其他类的对象使用 < association> 标签
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mapper.OrderMapper">

<!--    自定义映射关系,定义嵌套关系-->
    <resultMap id="orderMap" type="order">
<!--        第一层Order属性映射属性,Order的主键用id标签-->
        <id column="order_id" property="orderId"></id>
<!--        非主键标签-->
        <result column="order_name" property="orderName"></result>
        <result column="customer_id" property="customerId"></result>

<!--        给对象属性赋值-->
        <association property="customer" javaType="com.atguigu.pojo.Customer">
            <id column="customer_id" property="customerId"></id>
            <result column="customer_name" property="customerName"></result>
        </association>
    </resultMap>

    <select id="queryOrderById" resultMap="orderMap">
        select * from t_order tor join t_customer tur
           on tor.customer_id = tur.customer_id
            where tor.order_id = #{id}
    </select>
</mapper>

对多映射xml怎么写

  • 注意List列表的内部属性,使用< collection>标签
  • 注意< collection>标签中 指定类的属性名是ofType而不是 javaType
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mapper.CustomerMapper">

    <resultMap id="customerMap" type="customer">
        <id column="customer_id" property="customerId"/>
        <result column="customer_name" property="customerName"/>
<!--        对一的对象属性赋值-->
<!--        <association property=""></association>-->
        <collection property="orderList" ofType="com.atguigu.pojo.Order">
            <id column="order_id" property="orderId"/>
            <result column="order_name" property="orderName"/>
        </collection>
    </resultMap>

    <select id="queryList" resultMap="customerMap">
        select * from t_order tor join t_customer tur
        on tor.customer_id = tur.customer_id
    </select>

</mapper>

开启resultMap自动映射

mybatis-config.xml设置
< setting name="autoMappingBehavior" value="FULL"/>
除了id column,其他的属性名都会自动映射不用手动设置。


扫描二维码,在手机上阅读

推荐阅读: