MyBatis的关联映射(多对多查询)

目录

1.数据库准备

2.实体类

3.用户配置接口

4.用户配置文件 

5.解决方案

5.1 嵌套查询方式

5.2 嵌套结果查询


1.数据库准备

USE mybatis;
# 创建一个名称为tb_product的表
CREATE TABLE tb_product (
  id INT(32) PRIMARY KEY AUTO_INCREMENT,
  NAME VARCHAR(32),
  price DOUBLE 
 );
# 插入3条数据
INSERT INTO tb_product VALUES ('1', 'Java基础入门', '44.5');
INSERT INTO tb_product VALUES ('2', 'Java Web程序开发入门', '38.5');
INSERT INTO tb_product VALUES ('3', 'SSM框架整合实战', '50');
# 创建一个名称为tb_ordersitem 的中间表
CREATE TABLE tb_ordersitem (
    id INT(32) PRIMARY KEY AUTO_INCREMENT,
    orders_id INT(32),
    product_id INT(32),
    FOREIGN KEY(orders_id) REFERENCES tb_orders(id),
FOREIGN KEY(product_id) REFERENCES tb_product(id)
);
# 插入3条数据
INSERT INTO tb_ordersitem  VALUES ('1', '1', '1');
INSERT INTO tb_ordersitem  VALUES ('2', '1', '3');
INSERT INTO tb_ordersitem  VALUES ('3', '3', '3');
# 订单表tb_orders由于在上面已经创建,所以这里不用再次创建

2.实体类

 Orders.java

 

package com.biem.pojo;

import lombok.*;

import java.util.List;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Orders {
    private Integer id;
    private String number;
    private String userId;
    private Users users;
    private List<Product> productList;

}

Product.Java

package com.biem.pojo;

import lombok.*;

import java.util.List;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Product {
    private Integer id;
    private String name;
    private Double price;
    private List<Orders> ordersList;
}

3.用户配置接口

ProductMapper.java

4.用户配置文件 

ProductMapper.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">
<mapper namespace="com.biem.mapper.ProductMapper">

</mapper>

5.解决方案

5.1 嵌套查询方式

OrdersMapper.java 添加

package com.biem.mapper;

import com.biem.pojo.Orders;

import java.util.List;

public interface OrdersMapper {
    public List<Orders> selectOrders(Integer uid);
    public List<Orders> getOrders1(Integer userId);
    public List<Orders> getOrders1ByNestedResult(Integer userId);

    public List<Orders> findOrdersWithProduct(Integer id);

}

ProductMapper.java 添加

package com.biem.mapper;

import com.biem.pojo.Product;

import java.util.List;

public interface ProductMapper {
    public List<Product> findProductById(Integer id);

}

OrdersMapper.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">
<mapper namespace="com.biem.mapper.OrdersMapper">
    <select id="selectOrders" parameterType="Integer" resultType="Orders">
        select * from tb_orders where user_id=#{userId}
    </select>
    <select id="getOrders1" resultMap="ordersResult1">
        select * from tb_orders where user_id = #{userId}
    </select>
    <resultMap id="ordersResult1" type="orders">
        <result column="id" property="id"/>
        <result column="number" property="number"/>
        <association column="id" property="users" javaType="users" select="com.biem.mapper.UsersMapper.getUsersById"/>
    </resultMap>

    <!-- public List<Orders> getOrders1ByNestedResult(Integer userId); -->
    <select id="getOrders1ByNestedResult" resultMap="ordersResult2">
        <!-- id为接口中实现的方法名,resultMap为返回值类型,由于返回值包含一个Teacher对象,所以不能用resultType-->
        select o.id oid, o.number number, o.user_id uid , u.username username, u.address address
        from tb_orders o,tb_user u
        where o.user_id=u.id and o.user_id = #{userId}
    </select>
    <resultMap id="ordersResult2" type="orders">
        <result column="oid" property="id"/>
        <result column="number" property="number"/>
        <result column="uid" property="userId"/>
        <association property="users" javaType="users">
            <!--property是实体类中的字段属性,复杂的属性,使用了javaType描述的是属性的类型,它是一个Teacher对象-->
            <result property="id" column="uid"/>
            <result property="username" column="username"/>
            <result property="address" column="address"/>
        </association>
    </resultMap>
    <select id="findOrdersWithProduct" parameterType="Integer" resultMap="OrdersWithProductResult">
        select * from tb_orders where id = #{id}
    </select>
    <resultMap id="OrdersWithProductResult" type="Orders">
        <id property="id" column="id"></id>
        <result property="number" column="number"></result>
        <collection property="productList" column="id" ofType="Product" select="com.biem.mapper.ProductMapper.findProductById">
        </collection>
    </resultMap>


</mapper>

ProductMapper.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">
<mapper namespace="com.biem.mapper.ProductMapper">
    <!--public List<Product> findProductById(Integer id);-->
    <select id="findProductById" parameterType="Integer" resultType="Product">
        select * from tb_product where id in(
        select product_id from tb_ordersitem where orders_id = #{id}
        )
    </select>

</mapper>

OrderTest.java添加

package com.biem.test;

import com.biem.mapper.OrdersMapper;
import com.biem.pojo.Orders;
import com.biem.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;


public class OrdersTest {

    @Test
    public void testGetOrders1(){
        SqlSession session = MyBatisUtil.openSession();
        OrdersMapper mapper = session.getMapper(OrdersMapper.class);
        List<Orders> ordersList = mapper.getOrders1(1);
        System.out.println("ordersList = " + ordersList);
    }
    @Test
    public void testGetOrders2(){
        SqlSession session = MyBatisUtil.openSession();
        OrdersMapper mapper = session.getMapper(OrdersMapper.class);
        List<Orders> ordersList = mapper.getOrders1ByNestedResult(1);
        System.out.println("ordersList = " + ordersList);
    }
    @Test
    public void testFindOrdersWithProduct(){
        SqlSession session = MyBatisUtil.openSession();
        OrdersMapper mapper = session.getMapper(OrdersMapper.class);
        List<Orders> ordersList = mapper.findOrdersWithProduct(1);
        System.out.println("ordersList = " + ordersList);
    }

}

测试结果 

5.2 嵌套结果查询

 OrderMapper.java 添加

package com.biem.mapper;

import com.biem.pojo.Orders;

import java.util.List;

public interface OrdersMapper {
    public List<Orders> selectOrders(Integer uid);
    public List<Orders> getOrders1(Integer userId);
    public List<Orders> getOrders1ByNestedResult(Integer userId);

    public List<Orders> findOrdersWithProduct(Integer id);
    public List<Orders> findOrdersWithProductByNestedResult(Integer id);

}

OrdersMapper.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">
<mapper namespace="com.biem.mapper.OrdersMapper">
    <select id="selectOrders" parameterType="Integer" resultType="Orders">
        select * from tb_orders where user_id=#{userId}
    </select>
    <select id="getOrders1" resultMap="ordersResult1">
        select * from tb_orders where user_id = #{userId}
    </select>
    <resultMap id="ordersResult1" type="orders">
        <result column="id" property="id"/>
        <result column="number" property="number"/>
        <association column="id" property="users" javaType="users" select="com.biem.mapper.UsersMapper.getUsersById"/>
    </resultMap>

    <!-- public List<Orders> getOrders1ByNestedResult(Integer userId); -->
    <select id="getOrders1ByNestedResult" resultMap="ordersResult2">
        <!-- id为接口中实现的方法名,resultMap为返回值类型,由于返回值包含一个Teacher对象,所以不能用resultType-->
        select o.id oid, o.number number, o.user_id uid , u.username username, u.address address
        from tb_orders o,tb_user u
        where o.user_id=u.id and o.user_id = #{userId}
    </select>
    <resultMap id="ordersResult2" type="orders">
        <result column="oid" property="id"/>
        <result column="number" property="number"/>
        <result column="uid" property="userId"/>
        <association property="users" javaType="users">
            <!--property是实体类中的字段属性,复杂的属性,使用了javaType描述的是属性的类型,它是一个Teacher对象-->
            <result property="id" column="uid"/>
            <result property="username" column="username"/>
            <result property="address" column="address"/>
        </association>
    </resultMap>
    <select id="findOrdersWithProduct" parameterType="Integer" resultMap="OrdersWithProductResult">
        select * from tb_orders where id = #{id}
    </select>
    <resultMap id="OrdersWithProductResult" type="Orders">
        <id property="id" column="id"></id>
        <result property="number" column="number"></result>
        <collection property="productList" column="id" ofType="Product" select="com.biem.mapper.ProductMapper.findProductById">
        </collection>
    </resultMap>

    <!-- public List<Orders> findOrdersWithProductByNestedResult(Integer id); -->
    <select id="findOrdersWithProductByNestedResult" parameterType="Integer" resultMap="OrdersWithProductResult2">
        select o.*, p.id as pid, p.name, p.price
        from tb_orders o, tb_product p, tb_ordersitem oi
        where oi.orders_id=o.id and oi.product_id=p.id and o.id=#{id}
    </select>
    <resultMap id="OrdersWithProductResult2" type="Orders">
        <id property="id" column="id"></id>
        <result property="number" column="number"></result>
        <collection property="productList" ofType="product">
            <id property="id" column="pid"/>
            <result property="name" column="name"/>
            <result property="price" column="price"/>
        </collection>
    </resultMap>

</mapper>

OrderTest.java 添加

package com.biem.test;

import com.biem.mapper.OrdersMapper;
import com.biem.pojo.Orders;
import com.biem.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;


public class OrdersTest {

    @Test
    public void testGetOrders1(){
        SqlSession session = MyBatisUtil.openSession();
        OrdersMapper mapper = session.getMapper(OrdersMapper.class);
        List<Orders> ordersList = mapper.getOrders1(1);
        System.out.println("ordersList = " + ordersList);
    }
    @Test
    public void testGetOrders2(){
        SqlSession session = MyBatisUtil.openSession();
        OrdersMapper mapper = session.getMapper(OrdersMapper.class);
        List<Orders> ordersList = mapper.getOrders1ByNestedResult(1);
        System.out.println("ordersList = " + ordersList);
    }
    @Test
    public void testFindOrdersWithProduct(){
        SqlSession session = MyBatisUtil.openSession();
        OrdersMapper mapper = session.getMapper(OrdersMapper.class);
        List<Orders> ordersList = mapper.findOrdersWithProduct(1);
        System.out.println("ordersList = " + ordersList);
    }
    @Test
    public void findOrdersWithProductByNestedResult(){
        SqlSession session = MyBatisUtil.openSession();
        OrdersMapper mapper = session.getMapper(OrdersMapper.class);
        List<Orders> ordersList = mapper.findOrdersWithProductByNestedResult(1);
        System.out.println("ordersList = " + ordersList);
    }


}

测试结果

 

 

多对多关联查询是指两个表之间存在多对多的关系,需要通过中间表来进行关联查询。下面是一个简单的多对多关联查询的例子: 假设有两个表:学生表(students)和课程表(courses),它们之间存在多对多的关系,需要通过中间表(student_courses)来进行关联查询。 首先,创建三个表: ```sql CREATE TABLE students ( id INT PRIMARY KEY, name VARCHAR(50) ); CREATE TABLE courses ( id INT PRIMARY KEY, name VARCHAR(50) ); CREATE TABLE student_courses ( student_id INT, course_id INT, PRIMARY KEY (student_id, course_id), FOREIGN KEY (student_id) REFERENCES students(id), FOREIGN KEY (course_id) REFERENCES courses(id) ); ``` 然后,向三个表中插入一些数据: ```sql INSERT INTO students VALUES (1, 'Tom'); INSERT INTO students VALUES (2, 'Jerry'); INSERT INTO students VALUES (3, 'Alice'); INSERT INTO courses VALUES (1, 'Math'); INSERT INTO courses VALUES (2, 'English'); INSERT INTO courses VALUES (3, 'Science'); INSERT INTO student_courses VALUES (1, 1); INSERT INTO student_courses VALUES (1, 2); INSERT INTO student_courses VALUES (2, 2); INSERT INTO student_courses VALUES (3, 1); INSERT INTO student_courses VALUES (3, 3); ``` 最后,进行多对多关联查询: ```sql SELECT students.name, courses.name FROM students JOIN student_courses ON students.id = student_courses.student_id JOIN courses ON student_courses.course_id = courses.id; ``` 以上查询语句将返回所有学生和他们所选的课程。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值