[Mybatis] Many-to-many cascade query of cascade query

introduction

In Mybatis, many-to-many cascading queries are usually converted into two one-to-many cascading queries to implement
application scenarios. For example: the relationship between users and products is many-to-many, and an order can have multiple products. Use An intermediate table (order record table) can convert the many-to-many cascade into two one-to-many relationships

Create project and database tables

Create a Spring integration Mybatis project [Spring] Spring integration Mybatis case

Create orderstables, producttables, and order_producttables

DROP TABLE IF EXISTS `orders`;
CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `orderinfo` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `price` double(10,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `order_product`;
CREATE TABLE `order_product` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `order_id` int(11) DEFAULT NULL,
  `product_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `order_id` (`order_id`),
  KEY `product_id` (`product_id`),
  CONSTRAINT `order_id` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`),
  CONSTRAINT `product_id` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The project structure is as follows:
insert image description here

Create entity classes and database operation interfaces

Order class

public class Order {
    
    
    private int id;
    private String orderinfo;
    // 多对多中的另一个一对多
    private List<Product> products;
    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }
    public String getOrderinfo() {
    
    
        return orderinfo;
    }

    public void setOrderinfo(String orderinfo) {
    
    
        this.orderinfo = orderinfo;
    }

    public List<Product> getProducts() {
    
    
        return products;
    }

    public void setProducts(List<Product> products) {
    
    
        this.products = products;
    }

    @Override
    public String toString() {
    
    
        return "Order{" +
                "id=" + id +
                ", orderinfo='" + orderinfo + '\'' +
                ", products=" + products +
                '}';
    }
}

Product class

public class Product {
    
    
    private int id;
    private String name;
    private double price;
    // 多对多中的一个一对多
    private List<Order> orders;

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public double getPrice() {
    
    
        return price;
    }

    public void setPrice(double price) {
    
    
        this.price = price;
    }

    public List<Order> getOrders() {
    
    
        return orders;
    }

    public void setOrders(List<Order> orders) {
    
    
        this.orders = orders;
    }

    @Override
    public String toString() {
    
    
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", orders=" + orders +
                '}';
    }
}

OrderMapper class


@Repository("orderMapper")
@Mapper
public interface OrderMapper {
    
    
    List<Order> findAllOrdersAndProduct();
}

ProductMapper class

@Repository("productMapper")
@Mapper
public interface ProductMapper {
    
    
    List<Product> findAllProductAndOrders();
}

Create configuration file

mybatis-config.xml

<?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>
        <!--在使用MyBatis嵌套查询方式进行关联查询时,使用MyBatis的延迟加载可以在一定程度上提高查询效率-->
        <!--打开延迟加载的开关-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--将积极加载改为按需加载-->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    <mappers>
        <mapper resource="ProductMapper.xml"/>
        <mapper resource="OrderMapper.xml"/>
    </mappers>

</configuration>

OrderMapper.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.lucas.mybatis.mapper.OrderMapper">

    <resultMap id="orderAndProducts" type="com.lucas.mybatis.model.Order">
        <id property="id" column="id"></id>
        <result property="orderinfo" column="orderinfo"></result>
        <collection property="products" ofType="com.lucas.mybatis.model.Product"  >
            <id property="id" column="id"></id>
            <result property="name" column="name"></result>
            <result property="price" column="price"></result>
        </collection>
    </resultMap>
    <select id="findAllOrdersAndProduct"   resultMap="orderAndProducts">
      SELECT orders.*,product.id,product.`name`,product.price  FROM orders,product,order_product WHERE orders.id = order_product.order_id AND order_product.product_id = product.id;
    </select>
</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.lucas.mybatis.mapper.ProductMapper">

    <resultMap id="productAndOrders" type="com.lucas.mybatis.model.Product">
        <id property="id" column="id"></id>
        <result property="name" column="name"></result>
        <result property="price" column="price"></result>
        <collection property="orders" ofType="com.lucas.mybatis.model.Order"  >
            <id property="id" column="id"></id>
            <result property="orderinfo" column="orderinfo"></result>
        </collection>
    </resultMap>
    <select id="findAllProductAndOrders"   resultMap="productAndOrders">
     SELECT product.*,orders.id,orders.orderinfo FROM orders,product,order_product WHERE orders.id = order_product.order_id AND order_product.product_id = product.id;
    </select>
</mapper>

add test code

public class App {
    
    
    public static void main(String[] args) {
    
    
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        OrderMapper orderMapper = (OrderMapper) applicationContext.getBean("orderMapper");
        System.out.println("----订单列表-----");
        List<Order> orders = orderMapper.findAllOrdersAndProduct();
        for (Order order : orders) {
    
    
            System.out.println(order);
        }
        System.out.println("----商品列表列表-----");
        ProductMapper productMapper = (ProductMapper) applicationContext.getBean("productMapper");
        List<Product> products = productMapper.findAllProductAndOrders();
        for (Product product : products) {
    
    
            System.out.println(product);
        }
    }
}

The result of the operation is as follows:
insert image description here

Guess you like

Origin blog.csdn.net/huweiliyi/article/details/107924723