Mybatis series (4) – Basics – one to many

Time:2020-11-15

Step 1: one to many relationship between classification and product
Step 2: table structure
Step 3: prepare data
Step 4: run first, see the effect, and then learn
Step 5: imitation and troubleshooting
Step 6: effect
Step 7: product entity class
Step 8: modify the category entity class
Step 9: not required for the time being Product.xml
Step 10: modify Category.xml
Step 11: Test and run testmybatis

Step 1: one to many relationship between classification and product

In this knowledge point to do classification and product one to many relationship, based on the mybatis introductory tutorial.

One category corresponds to multiple products

Step 2: table structure

The classification table does not change and the new product list is added

use how2java;
create table product_(
        id int NOT NULL AUTO_INCREMENT,
        name varchar(30)  DEFAULT NULL,
        price float  DEFAULT 0,
        cid int ,
        PRIMARY KEY (id)
)AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Step 3: prepare data

Clear category_ And product_ surface
Add 2 pieces of classified data with ID of 1 and 2
Six new product data are added, and the above two classified data are associated respectively

use how2java;
delete from category_;
INSERT INTO category_ VALUES (1,'category1');
INSERT INTO category_ VALUES (2,'category2');
delete from product_;
INSERT INTO product_ VALUES (1,'product a', 88.88, 1);
INSERT INTO product_ VALUES (2,'product b', 88.88, 1);
INSERT INTO product_ VALUES (3,'product c', 88.88, 1);
INSERT INTO product_ VALUES (4,'product x', 88.88, 2);
INSERT INTO product_ VALUES (5,'product y', 88.88, 2);
INSERT INTO product_ VALUES (6,'product z', 88.88, 2);

Step 4: run first, see the effect, and then learn

As the old rule, first download the executable items in the download area (click to enter), configure and run them, and then learn what steps to do to achieve this effect.

Step 5: imitation and troubleshooting

After making sure that the runnable project runs correctly, follow the steps of the tutorial and imitate the code again.
It is inevitable that there is code discrepancy in the simulation process, which leads to the failure to get the expected running resultsright key(can run the project) and your own code to locate the problem.
In this way,Learning is effective and troubleshooting is efficientIt can obviously improve the learning speed and cross the threshold of learning.

It is recommended to use diffmerge software for folder comparison. Compare your own project folder with my runnable project folder.
This software is very powerful, you can know which two files in the folder are wrong, and mark them out clearly
Here is a green installation and use tutorial: diffmerge download and use tutorial

Step 6: effect

Mybatis series (4) - Basics - one to many

Step 7: product entity class

A common POJO

package com.how2java.pojo;

public class Product {
    private int id;
    private String name;
    private float price;
    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 float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", price=" + price + "]";
    }
}

Step 8: modify the category entity class

Modify the category entity class to provide a collection of products

package com.how2java.pojo;

import java.util.List;

public class Category {
    private int id;
    private String name;
    List<Product> products;
    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 List<Product> getProducts() {
        return products;
    }
    public void setProducts(List<Product> products) {
        this.products = products;
    }
    @Override
    public String toString() {
        return "Category [id=" + id + ", name=" + name + "]";
    }
}

Step 9: not required for the time being Product.xml

This example demonstrates that one to many of the products can be classified, which is unnecessary for the time being Product.xml

Step 10: modify Category.xml

The left join Association query is used to query the category and product tables.
Different from the previous study, we do not use the resulttype, but the resultmap. Through the resultmap, we can get the data and put it in theCorrespondingObject properties
notes: the ID field of category has the same name as the ID field of product. Mybatis does not know who owns it, so it needs to distinguish it by taking the alias CID and PID.
The same is true for the name field.

<?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.how2java.pojo">
    <resultMap type="Category" id="categoryBean">
        <id column="cid" property="id" />
        <result column="cname" property="name" />
        <! -- one to many relationship -- >
        <! -- property: refers to the value of the collection property, oftype: refers to the type of the element in the collection -- >
        <collection property="products" ofType="Product">
            <id column="pid" property="id" />
            <result column="pname" property="name" />
            <result column="price" property="price" />
        </collection>
    </resultMap>

    <! -- associate query classification and product table -- >
    <select id="listCategory" resultMap="categoryBean">
            select c.*, p.*, c.id 'cid', p.id 'pid', c.name 'cname', p.name 'pname' from category_ c left join product_ p on c.id = p.cid
        </select>
</mapper>

Step 11: Test and run testmybatis

Mybatis series (4) - Basics - one to many

package com.how2java;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.how2java.pojo.Category;
import com.how2java.pojo.Product;

public class TestMybatis {
    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        List<Category> cs = session.selectList("listCategory");
        for (Category c : cs) {
            System.out.println(c);
            List<Product> ps = c.getProducts();
            for (Product p : ps) {
                System.out.println("\t" + p);
            }
        }
        session.commit();
        session.close();
    }
}

To learn more, click on: https://how2j.cn/k/mybatis/mybatis-one-to-many/1089.html

Recommended Today

Summary of recent use of gin

Recently, a new project is developed by using gin. Some problems are encountered in the process. To sum up, as a note, I hope it can help you. Cross domain problems Middleware: func Cors() gin.HandlerFunc { return func(c *gin.Context) { //Here you can use * or the domain name you specify c.Header(“Access-Control-Allow-Origin”, “*”) //Allow header […]